5

我想在 UITableView 的页脚中显示一个 UIButton(应该与页眉完全相同)。

这段代码在我的 TableViewController 的 viewDidLoad 中:

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);

但是,此代码不起作用。Button 的宽度太大了,它是 320。(虽然高度是正确的。)第一个 NSLog 输出 70,第二个和第三个输出 320。所以看起来 setTableFooterView 方法奇怪地调整了按钮的大小。

我通过将 UIButton 放在另一个 UIView 中,然后将其设置为表页脚解决了这个问题:

 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];

这有效,按钮具有正确的宽度。

但是,我不明白为什么第一个代码示例不起作用。谁能解释一下?

4

2 回答 2

19

无论您为要添加为UITableView页脚/页眉的视图设置什么宽度 - 它的宽度始终与表格的宽度相同。

因此,在您的情况下,您添加的视图的大小已调整为CGRectMake(0, 0, 320, 50),但按钮仍保留在正确的框架中。按钮的框架是根据视图...

编辑
页脚/页眉框架中唯一保留的参数是高度。

请注意,如果您在将页眉/页脚视图添加到表格后更改其高度,则不会进行任何更改。您应该在将其添加到表格之前设置高度...

于 2010-07-19T12:31:00.413 回答
3

实际上,我遇到了一种试图克服这个问题的方法;

创建一个空的 UIView 320x(按钮的高度),然后将按钮置于此包含视图的中心。这样视图内的按钮不会被调整大小。

希望这可以帮助,

乔纳森

于 2012-07-31T14:10:14.033 回答