UITableView tableFooterView weird resizing

≡放荡痞女 提交于 2020-01-12 08:22:09

问题


I want to display a UIButton in a UITableView's Footer (should be exactly the same for the header).

This code is in the viewDidLoad of my TableViewController:

UIButton *footerShareButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[footerShareButton setFrame:CGRectMake(10, 0, 70, 50)];
NSLog(@"%f", footerShareButton.frame.size.width);

[self.tableView setTableFooterView:footerShareButton];

NSLog(@"%f", footerShareButton.frame.size.width);
NSLog(@"%f", self.tableView.tableFooterView.frame.size.width);

However, this code doesn't work. The Button's width is much too large, it's 320. (The height is correct though.) The first NSLog outputs 70, the second and the third output 320. So it seems like the setTableFooterView method strangely resizes the button.

I have solved this problem by putting the UIButton in another UIView before setting it as the table footer:

 UIButton *footerShareButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 [footerShareButton setFrame:CGRectMake(10, 0, 70, 50)];

 UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 70, 50)];
 [aView addSubview:footerShareButton];

 [self.tableView setTableFooterView:aView];
 [aView release];

This works, the button has the correct width.

However, I don't understand why the first code sample doesn't work. Can anyone explain?


回答1:


No matter what width you set to the view that you are adding as a UITableView footer/header - its width always will be the same as the table's width.

So, in your case the view that you've added is resized to CGRectMake(0, 0, 320, 50), but the button remains with the correct frame. Button's frame is according to the view...

EDIT:
The only parameter in footer's/header's frame that remains as you set it is the height.

Notice that if you will change the height of the header/footer view after it is added to the table it won't make any change. You should set the height before adding it to the table...




回答2:


There is actually a way which I came across trying to overcome this problem;

Create an empty UIView 320x(the height of your button) and then place the button centred inside this containing view. This way the button inside the view doesn't get resized.

Hope this helps,

Jonathan



来源:https://stackoverflow.com/questions/3280841/uitableview-tablefooterview-weird-resizing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!