以编程方式将 UIButton 添加到 UITableView 但按钮不显示

Posted

技术标签:

【中文标题】以编程方式将 UIButton 添加到 UITableView 但按钮不显示【英文标题】:Add UIButton to UITableView programmatically but the button doesn't show 【发布时间】:2016-01-30 14:07:30 【问题描述】:

我想在表格视图上方添加一个按钮,而不是随着表格视图滚动。但是按钮不显示。有什么想法吗?

UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
[refreshButton setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
CGRect applicationFrame = [UIScreen mainScreen].bounds;
CGFloat screenWidth = CGRectGetWidth(applicationFrame);
CGFloat screenHeight = CGRectGetHeight(applicationFrame);
CGFloat buttonWidth = 40.0f;
CGFloat buttonHeight = 40.0f;
CGFloat spacing = 10.0f;
CGFloat buttonX = screenWidth - buttonWidth - spacing;
CGFloat buttonY = screenHeight - buttonHeight - spacing;
CGRect buttonFrame = CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight);
refreshButton.frame = buttonFrame;
[refreshButton addTarget:self
                  action:@selector(clickRefreshButton)
        forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:refreshButton];

提前致谢!

【问题讨论】:

将按钮添加到表头视图 仍然没有出现:( 如果将butotn添加到表头视图,它将被滚动到表视图。 您发布的代码不会将按钮添加到表格视图。它将按钮添加到视图中,由表视图覆盖。 我检查了视图层次,但没有按钮,没有被表格视图覆盖。另外,如果我将它作为子视图添加到表视图中,它也不会显示。 【参考方案1】:

UITableViewController 无法做到这一点。原因:视图控制器的view属性表格视图,所以不能在上面添加任何东西。

这样做的方法是使用普通的UIViewController 并添加您的按钮和UITableView 作为子视图(在Interface Builder 中比在代码中更好,顺便说一句)。

为了使表格视图按预期工作,您必须添加

表格视图的出口 采用UITableViewDataSourceUITableViewDelegate 协议 与UITableViewController 一样,至少实现必要的数据源方法

【讨论】:

好吧,我想知道为什么我不能将 uibutton 添加到 uitableview 上,因为 uitableview 继承自 uiview? 但它也继承自UIScrollView,所以事情变得复杂了。滚动视图的子视图的处理方式不同(即它们滚动;-))。 那么如果我使用UIViewController并在self.view中添加一个按钮那么这意味着tableView和按钮都是self.view的子视图,它们是并行的? 好的。让我试试看。 我在storyboard的一个UIViewController中设置了tableView,并设置了所有的outlet(包括tableview、datasource、delegate),也让viewController采用了UITableViewDataSource和UITableViewDelegate协议,并实现了必要的方法.但是当我运行应用程序时没有任何显示。事实证明,numberOfSectionsInTableView:tableView:numberOfRowsInSection:tableView:cellForRowAtIndexPath: 根本没有执行。你知道为什么吗?

以上是关于以编程方式将 UIButton 添加到 UITableView 但按钮不显示的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式将 UIButton 添加到 rootview,我做错了啥?

以编程方式将 UIButton 添加到 UITableView 但按钮不显示

如何以编程方式将 UIButton 添加到 UIToolBar?

以编程方式将 UIButton 添加到带有情节提要的自定义 ViewController

以编程方式将 UIButton 添加到 UINavigationBar 的子视图,并且触摸事件未注册

Swift:以编程方式在键盘上方添加 UIButton