OGeek|极客世界-中国程序员成长平台

标题: ios - 在 viewDidLoad 中设置约束无效 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:17
标题: ios - 在 viewDidLoad 中设置约束无效

我注意到在某些情况下,在 viewDidLoad 中激活约束不起作用。这是一个示例,在我的情况下应该有效但无效

override func viewDidLoad() {
    super.viewDidLoad()
    //constrain is not active
    constrain.active = true
    view.layoutIfNeeded()
    //constrain is active
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    //constrain is not active anymore
}

现在有更多代码,我设置了一些 UIImages、UILabels、隐藏 UIViews 但没什么特别的。似乎我在 UIScrollViewUIStackView

的 View 中一直遇到这个问题

顺便说一句,如果我调用 constrain.active = true & view.layoutIfNeeded() 两次,一切正常。添加无视延迟也可以解决问题

override func viewDidLoad() {
    super.viewDidLoad()
    delay(0) {
        self.buttonStackBottomConstrain.active = true
        self.view.layoutIfNeeded()
    }
}

func delay(delayouble, closure)->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

任何想法为什么会发生这种情况?



Best Answer-推荐答案


当调用 viewDidLoad:viewWillAppear: 时, View 还不可见,因此将代码放入 viewDidAppear: 时, View 可见当时。添加延迟也可以作为 viewDidAppear: 现在调用,无论哪种方式都是一样的。

viewDidAppear: called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen. This method simply indicates that the content view has been added to the app’s view hierarchy.

由于内容 View 已添加到应用程序的 View 层次结构中,因此一旦 View 出现在屏幕上,它的所有约束都可以修改。

生命周期方法和所有 UIKit 交互一样在 mainThread 上运行。任何这些方法的延迟都会导致实际的延迟。

Apple Docs View Controller Lifecycle

关于ios - 在 viewDidLoad 中设置约束无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024750/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4