【问题标题】:Updating Main.storyboard constraints programatically (Swift)以编程方式更新 Main.storyboard 约束 (Swift)
【发布时间】:2021-12-20 09:01:06
【问题描述】:

我想将我的 textview 的底部锚点更新为等于键盘高度的常量,这样它就不会覆盖 textView 中的文本。我在 Main.storyboard 中有一个约束标识符为我的 textView 设置为“bottomTextViewConstraint”,我们还有以下代码:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                    print("This prints")
            for constraint in self.textView.constraints {
                    print("This does not print")
                if constraint.identifier == "bottomTextViewConstraint" {
                    constraint.constant = keyboardSize.height
                    print("This does not print")
                }
            }
            textView.updateConstraints()
        }
    }
}

self.textView.constraints 为零...似乎以编程方式我无法访问我在情节提要中设置的内容。任何想法为什么?

【问题讨论】:

    标签: ios swift textview constraints xcode-storyboard


    【解决方案1】:

    将文本视图的底部锚点与其超级视图的底部锚点相关的约束添加到文本视图的超级视图,因此您在textView.constraints 中找不到它。

    一个更简单的方法是从情节提要中添加一个 IBOutlet:

    @IBOutlet var bottomConstraint: NSLayoutConstraint!
    

    右键单击故事板中的视图控制器,然后将bottomConstraint 连接到大纲视图中显示的约束:

    然后您可以删除整个 for 循环并将其替换为:

    bottomConstraint.constant = keyboardSize.height
    

    【讨论】:

    • 是的,完美,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2015-07-15
    • 2015-06-10
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多