【发布时间】:2015-06-05 22:59:00
【问题描述】:
我正在尝试以编程方式使用约束将带有width = 40 的箭头按钮置于屏幕中间。
如果我在 viewDidAppear 中调用它,我的代码可以工作,但在 viewDidLoad 中崩溃。
将它放在viewDidAppear 中会让人眼花缭乱,因为您看到屏幕然后看到按钮跳到屏幕中间。任何想法如何在视图之前设置它是显示了吗?
我可能会添加这是一个子视图,所以我从一个视图不同的 viewController 调用 centerArrow()。
所以在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)
}
【问题讨论】:
-
呃...
NSLayoutAttributeCenterX? -
@nhgrif 没有详细说明这对我不起作用,因为子视图实际上比屏幕大。
-
这无关紧要。如果视图需要彼此居中,那么它们的宽度或它们是否完全适合屏幕都没有关系...这不会影响
NSLayoutAttributeCenterX...
标签: ios swift autolayout uikit nslayoutconstraint