我正在尝试以编程方式使用约束将带有 width = 40
的箭头按钮居中。
如果我在 viewDidAppear
中调用它,我的代码可以正常工作,但在 viewDidLoad
中崩溃。
将它放在 viewDidAppear
中是一种眼睛疼痛,因为您看到屏幕然后看到按钮跳到屏幕中间。知道如何设置它在显示 View 之前?
我可能会补充说这是一个 subview ,所以我从一个 viewController
调用 centerArrow()
,它的 View 不是同一个 View 。
所以在 viewController
中:
let pview = NSBundle.mainBundle().loadNibNamed("Profile", owner: nil, options: nil)[0] as! ProfileView
override func viewDidAppear(animated: Bool) {
pview.centerArrow()
}
在继承UIView
的ProfileView
中:
func centerArrow()
{
let screenSize: CGRect = UIScreen.mainScreen().bounds
let width = (screenSize.width / 2) - 20
let constraint = NSLayoutConstraint(item: arrowButton, attribute: NSLayoutAttribute.LeftMargin, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.LeftMargin, multiplier: 1, constant: width)
self.addConstraint(constraint)
}
最佳答案
尝试使用 viewDidLayoutSubViews
,这可能会提供您在这种情况下寻找的时间。
关于ios - 在看到 View 之前添加约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677038/