好吧,在界面构建器 (Main.storyboard
) 中,我在 UIScrollView
中嵌入了一个 containerView:UIView
。在 containerView
中,我想创建额外的 UIView
来保存内容 block ,例如标题、正文等。这样做的原因是内容可以垂直滚动但不能水平滚动。
我的目标是使用自动布局来创建这些不同的UIView
。截至目前,containerView 会根据所使用设备的屏幕尺寸自动调整其宽度,以防止水平滚动。它使用我为宽度约束创建的 IBOutlet 来执行此操作。目前看起来像这样:
@IBOutlet var containerView: UIView!
@IBOutlet var containerViewWidthConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
//Prevents horizontal scrolling
containerViewWidthConstraint.constant = self.view.frame.size.width
createHeader()
}
然后我创建了一个名为 createheader{}
的函数,它将 headerView:UIView
固定在 containerView
的顶部,并从containerView
的任一边缘:
func createHeader() {
//Create header
let headerView = UIView()
headerView.backgroundColor = UIColor.blueColor()
self.containerView.addSubview(headerView)
//Create header constraints
let leftMargin = NSLayoutConstraint(item: headerView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1.0, constant: 8)
let rightMargin = NSLayoutConstraint(item: containerView, attribute: .Trailing, relatedBy: .Equal, toItem: headerView, attribute: .Trailing, multiplier: 1.0, constant: 8)
let topMargin = NSLayoutConstraint(item: headerView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1.0, constant: 70)
let heightConstraint = NSLayoutConstraint(item: headerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 160)
//Activate header constraints
headerView.setTranslatesAutoresizingMaskIntoConstraints(false)
NSLayoutConstraint.activateConstraints([leftMargin,rightMargin,topMargin,heightConstraint])
println(headerView.frame.size.width)
}
现在,由于 headerView
内内容的大小将取决于所使用设备的屏幕大小,我希望能够创建根据以下内容调整内容宽度的函数headerView
本身的宽度大小。然而,每次我尝试使用以下方法获取 headerView
的宽度:
println(headerView.frame.size.width)
它返回一个零值,显然情况并非如此,因为它仍然根据上面的约束创建一个蓝色背景的 headerView
。
为什么 SWIFT 无法识别 headerView
有宽度?我怎样才能获取headerView
的宽度?
最佳答案
安装约束后,如果您想立即更新框架,则需要调用layoutIfNeeded
。
func createHeader() {
//Create header
let headerView = UIView()
headerView.backgroundColor = UIColor.blueColor()
self.containerView.addSubview(headerView)
...
//Activate header constraints
headerView.setTranslatesAutoresizingMaskIntoConstraints(false)
NSLayoutConstraint.activateConstraints([leftMargin,rightMargin,topMargin,heightConstraint])
self.containerView.layoutIfNeeded() // Updates the frames
println(headerView.frame.size.width) // Will output the correct width
}
请注意,这将在 UI 循环的下一次迭代中自动发生,但是,当您想立即查看效果时,这对您没有帮助。
关于ios - 使用自动布局确定 UIView 的宽度 - SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31948123/