导航控制器推送后topLayoutGuide移动

时间:2016-10-22 20:48:57

标签: ios iphone swift nslayoutconstraint

我有一个简单的视图控制器层次结构,其中一个视图控制器使用UINavigationController显示。在viewDidLoad中,它使用约束设置其视图。在视图完全可见之前(动画期间),topLayoutGuide是状态栏,当视图完全在屏幕上时,它将变为UINavigationBar的底部。这会导致视图跳跃。

删除“在顶栏下延伸边缘”选项可修复此问题,但会使导航栏出现不需要的灰色渐变,只能通过设置导航栏的backgroundColor来部分纠正。

即使在动画期间,有没有办法让topLayoutGuide引用导航栏的底部?这之前有用,但它不适用于iOS 10中的Xcode 8.0。

1 个答案:

答案 0 :(得分:4)

通过评论大块代码,我发现了一个从viewDidLoad()调用的设置函数的罪魁祸首。抱歉,我的问题没有包含足够的细节来解决它。如果将来有人看到这种症状,这里是重新创建错误的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel(frame: CGRect.zero)
    label.text = "Testing"
    label.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(label)
    self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
    self.view.layoutIfNeeded()
}

解决方案是删除layoutIfNeeded()电话。约束在viewDidLoad()之后生效,在其中调用layoutIfNeeded()会暂时与topLayoutGuide混在一起。