iOS Autolayout - viewDidLayoutSubviews 中未设置帧大小 [英] iOS Autolayout - Frame size not set in viewDidLayoutSubviews

查看:15
本文介绍了iOS Autolayout - viewDidLayoutSubviews 中未设置帧大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 iOS 8 的键盘,使用 Autolayout 将按钮放置在视图上.
当我使用约束更改布局时,屏幕上的所有内容都正确显示,但是当我想知道视图的帧大小时,我没有得到正确的大小.

I'm working on a keyboard for iOS 8 using Autolayout to place the buttons on the view.
When I'm changing the layout using constraints, everything is appearing correctly on the screen, but when I want to know the view's frame size, I don't get the right size.

例如:我按下一个键,键盘布局会根据我的约束改变和布局.然后我想知道屏幕上任何按钮的大小 - 我在viewDidLayoutSubviews"中执行此操作并在控制台中获得结果:

For example: I press a key, the keyboard layout changes and layouts everything according to my constraints. Then I want to know the size of any button on the screen - I do that in "viewDidLayoutSubviews" and get that result in the console:

2014-10-29 12:27:09.088 Keyboard[2193:60674] view did layout subviews
2014-10-29 12:27:09.088 Keyboard[2193:60674] {{inf, inf}, {0, 0}}

按钮具有正确的大小和正确的位置,但是在尝试获取其框架时未设置大小.

The button has the correct size and correct position, but when trying to get its frame the size is not set.

当我的代码在 viewDidLayoutSubviews 中不起作用时,我必须把它放在哪里?

Where do I have to put my code when it is not working in viewDidLayoutSubviews?

我在 stackoverflow 和其他网站上发现了很多问题,但没有一个涵盖我的问题.

I found a lot of questions on stackoverflow and other websited, but none of them covered my question.

推荐答案

我遇到了一个非常相似的问题(upvoted question),发现 beeef's回答 指向正确的方向.鉴于 Apple 的文档说不要直接调用 layoutSubviews(),我改为执行以下操作(其中 mySubView 是 self.view 的直接子视图):

I encountered a very similar issue (upvoted question) and found beeef's answer to point in the right direction. Given that Apple's documentation says not to call layoutSubviews() directly, I instead did as follows (where mySubView is a direct subview of self.view):

override func viewDidLayoutSubviews() {
    // self.view's direct subviews are laid out.
    // force my subview to layout its subviews:
    self.mySubView.setNeedsLayout()
    self.mySubView.layoutIfNeeded()

    // here we can get the frame of subviews of mySubView
    // and do useful things with that...
}

仅供参考,在我的情况下,mySubView 是一个 UIScrollView,我需要获取其中一个子视图的框架,以便我可以在视图出现之前相应地设置 contentOffset.我不确定 viewDidLayoutSubviews() 是否是执行此操作的最佳位置,但它可以确保 mySubView 已布局.

Just FYI, in my case mySubView is a UIScrollView, and I need to get the frame of one of its subviews, such that I can set the contentOffset accordingly before the view appears. I'm not sure whether viewDidLayoutSubviews() is the best place to do this, but it ensures that mySubView has been laid out.

这篇关于iOS Autolayout - viewDidLayoutSubviews 中未设置帧大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆