繁体   English   中英

将子视图添加到UITableViewController

[英]Adding a subview to a UITableViewController

我正在使用带有一些单元格的UITableViewController。 我的问题是我需要在表格视图前面有一个静态按钮,但是当我添加按钮视图时,它随表格视图滚动而上下移动。
这是我在viewDidLoad中的代码:

[button setFrame:CGRectMake(self.view.frame.size.width - 55, self.view.frame.size.height - 55, 50, 50)];
[button setBackgroundColor:[UIColor redColor]];
[[button layer]setMasksToBounds:YES];
[[button layer]setCornerRadius:25.0];

[self.view addSubview:button];
[self.view bringSubviewToFront:button];

我将这一行添加到viewWillLayoutSubviews中以支持方向:

[button setFrame:CGRectMake(self.view.frame.size.width - 55, self.view.frame.size.height - 55, 50, 50)];

无论tableview内容视图的偏移量如何,我都需要使按钮静态。 有人知道我在做什么错吗?

编辑

经过测试您的答案,这解决了我的问题:

我在viewWillLayoutSubviews方法中将contentOffset.y添加到按钮的setFrame中。 我也尝试使用scrollView委托,但并不需要它,因为第一种方法正在完成所有工作。

    - (void)viewWillLayoutSubviews
{
    [button setFrame:CGRectMake(self.view.frame.size.width - 55, self.tableView.contentOffset.y + self.view.frame.size.height - 110, 50, 50)];
}

就是这样,按钮保持静态。

按钮y原点的额外负110是因为我在视图中拥有的高度和tabBar

谢谢大家。 您的回答确实很有帮助。

您在这里有2个选项。

  1. 转换为使用带有UITableViewUIViewController而不是使用UITableViewController 不需要太多工作,然后可以将UITableView和按钮都添加为根UIView子视图。

  2. 如果要继续使用UITableViewController ,则需要实现scrollViewDidScroll:并在滚动表时修改按钮的框架,以使其显示为静态。 您可能还需要向表中添加一个contentInset ,以便您可以将内容滚动到自定义视图之外。

如果您的表tableview只有1个部分,则还可以将此button添加为该部分的标题

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   // Build my view and return it
}

- (CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section
{
   // Return the height
}

您的UITableViewController必须是tableView的scrollViewDelegate 实现scrollViewDidScroll:更改按钮的框架/位置。

一个示例是,将按钮的origin.y设置为scrollView.contentOffset.y应该使按钮与tableView的顶部保持齐平。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM