iOS:在屏幕上添加具有固定位置的 subview

标签 ios xcode uiview position

如何固定 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,这会更容易一些,但无论如何也不难。

UITableViewUIScrollView 的子类,因此 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/

相关文章:

objective-c - 在 React Native 0.61.2 中找不到“React/RCTBridgeModule.h”文件

ios - 在 IOS 中将一个 uiview 的 Action 传递给另一个

ios - Convert UIView 转换从 View A 到 View B

xcode - 冗余一致性错误消息 Swift 2

ios - 使用 Cordova 2.4、Xcode 5 的 Apple Mach-O 链接器错误

ios - 1个按钮,播放10个声音?

ios - iOS 的 Facebook 登录未返回

iphone - 如何正确地从 Three20 库中删除组件

ios - 我真的需要导航 Controller 吗?

ios - ?尝试将数据源加载到 UIPickerView 时返回