在查看视图之前添加约束?

时间:2015-06-05 22:59:01

标签: ios swift autolayout uikit nslayoutconstraint

我正在尝试以编程方式使用约束在屏幕中间放置一个带有width = 40的箭头按钮。

如果我在viewDidAppear中调用它,但在viewDidLoad中崩溃,则我的代码有效。

将它放在viewDidAppear是一个眼睛疼痛,因为你看到屏幕,然后看到按钮跳到屏幕中间。任何想法如何设置它之前视图显示?

我可能会添加这是一个子视图,因此我从centerArrow()调用viewController,其视图的视图不同。

所以在viewController

let pview = NSBundle.mainBundle().loadNibNamed("Profile", owner: nil, options: nil)[0] as! ProfileView


override func viewDidAppear(animated: Bool) {
    pview.centerArrow()
}

ProfileView内继承UIView

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)
}

1 个答案:

答案 0 :(得分:1)

尝试使用viewDidLayoutSubViews,这可能会提供您在这种情况下寻找的时间。

相关问题