UIView的frame渲染大于frame

UIView's frame rendering larger than frame

我正在尝试向 UIScrollView 添加子视图。首先,我从情节提要中实例化视图控制器,然后将视图的框架设置为应用程序边界。当我将视图添加到 UIScrollView 时,它明显比预期的要大。

CGRect mainFrame = CGRectMake(0, topButtonHeight, screenWidth, screenHeight);

feelingVC = (FeelingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"feelingVC"];
feelingVC.delegate = self;
feelingView = feelingVC.view;
[feelingView setFrame:mainFrame];
[self.scrollView addSubview:feelingView];

我能看出来是因为它的背景颜色超出了它应该在的位置。 XCode 中的 "Debug View Hierarchy" 模式也证实了这一点。但是,如果我检查视图的框架,它会打印出它应该是什么,而不是它实际是什么。

相同大小但完全以编程方式生成的视图,可以正常工作:

mainView = [[UIView alloc] initWithFrame:mainFrame];
mainView.backgroundColor = [UIColor blackColor];
[self.scrollView addSubview:mainView];

我不确定是什么导致了这个问题 - 我已经从他们的视图控制器实例化了其他视图,也通过故事板,并毫无问题地设置了他们的框架。

EDIT:这是从包含 UIScrollView 的视图控制器的 viewDidLoad 调用的。 screenWidth & screenHeight 是这样计算的(它们是实例变量):

screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;

尝试用viewWillAppear方法设置视图框。

viewDidLoad 不是设置框架的好地方(因为它只在加载视图时调用一次。),UI 组件尚未由系统正确配置。

此外,更喜欢使用:

screenWidth = [UIScreen mainScreen].bounds.size.width;
screenHeight = [UIScreen mainScreen].bounds.size.height;

而不是

screenWidth = [UIScreen mainScreen].applicationFrame.size.width;
screenHeight = [UIScreen mainScreen].applicationFrame.size.height; 

因为在这种情况下,考虑到设备的方向,边界具有正确的位置信息。

或者你可以这样做,在 viewDidLoad: 方法

中初始化 mainView 之后
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    mainView.frame = [UIScreen mainScreen].bounds;
}

您还可以添加此内容以在更新子视图时重新配置视图框架:

- (void)viewWillLayoutSubviews { //or viewDidLayoutSubviews
    [super viewWillLayoutSubviews];
    mainView.frame = [UIScreen mainScreen].bounds;
}