如何固定 subview 在屏幕上的位置(尤其是在 UIScrollView 和 UITableView 中)?我认为在 Storyboard中
[self.view addSubview:aSubView];
不再工作了。
有什么想法吗?
编辑 #1:我使用的是 UITableViewController,而不是简单的 UITableView。
编辑#2:
CGRect fixedFrame = self.menuViewRelative.frame;
fixedFrame.origin.y = 0 + scrollView.contentOffset.y;
self.menuViewRelative.frame = fixedFrame;
menuViewRelative = [[UIView alloc] init];
menuViewRelative.backgroundColor = [UIColor grayColor];
menuViewRelative.frame = CGRectMake(0.0, 0.0, 320.0, 50.0);
[self.view addSubview:self.menuViewRelative];
最佳答案
正如其他人指出的那样,如果您不使用 UITableViewController
,这会更容易一些,但无论如何也不难。
UITableView
是 UIScrollView
的子类,因此 TableView 的委托(delegate)(在本例中是您的 UITableViewController
实例)也将接收 UIScrollViewDelegate
方法调用。您所要做的就是实现每次滚动偏移量更改时调用的方法并调整“固定” View 的框架。
像这样:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGRect fixedFrame = self.fixedView.frame;
fixedFrame.origin.y = 20 + scrollView.contentOffset.y;
self.fixedView.frame = fixedFrame;
}
将 20 替换为您希望它距离表格 View 顶部的点数。您仍将 self.fixedView
添加为 self.view
的 subview ,这只会确保它看起来像是在表格 View 上方的固定位置。
编辑:根据您发布的代码,我猜您的版本应该如下所示:
- (void)viewDidLoad {
menuViewRelative = [[UIView alloc] init];
menuViewRelative.backgroundColor = [UIColor grayColor];
menuViewRelative.frame = CGRectMake(0.0, 0.0, 320.0, 50.0);
[self.view addSubview:self.menuViewRelative];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
CGRect fixedFrame = self.menuViewRelative.frame;
fixedFrame.origin.y = 0 + scrollView.contentOffset.y;
self.menuViewRelative.frame = fixedFrame;
}
关于iOS:在屏幕上添加具有固定位置的 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663230/