以一个标识符在Interface

以一个标识符在Interface

本文介绍了有没有一种方法,以一个标识符在Interface Builder添加到自动布局限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Interface Builder做一些视觉上的布局后,我创造了一些限制,我想在运行时访问。有没有一种方法来标记或在Interface Builder找出制约,使他们能够看行动以后呢?

After doing some visual layout in Interface Builder I've created some constraints that I want to access at runtime. Is there a way to label or identify constraints in Interface Builder so they can be looked-up later?

我想这样做的原因是,我需要对那些在视觉上指定的约束执行一些计算基数。我知道,苹果提供了Visual格式语言,我可以在控制器编程方式指定的约束。我宁可不使用这种方法,所以我不会失去IB的设计时间反馈。

The reason I want to do this is I need to perform some calculation base upon the constraints that are visually specified. I am aware that Apple has provided the Visual Format Language and I could specify the constraints programmatically in a controller. I rather not use this approach so I don't lose the design time feedback of IB.

将参照插座没有工作,但问题仍然有效。

Making a referencing outlet did work, but the question still stands.

推荐答案

是的,这是可以做到。 NSLayoutConstraint 有一个名为属性标识符,无法在界面生成器的暴露和分配。为了演示这一点,我创建了一个的单查看应用程序的,有一个单独的子视图是一个红色的盒子。此子视图有4个限制:宽度,高度,水平在容器中心,集装箱垂直居中。我给宽度约束标识符 redBoxWidth 通过执行以下操作:

Yes, this can be done. NSLayoutConstraint has a property called identifier than can be exposed in Interface Builder and assigned. To demo this, I created a Single View Application that has a single subview that is a red box. This subview has 4 constraints: width, height, centered horizontally in container, centered vertically in container. I gave the width constraint the identifier redBoxWidth by doing the following:


  1. 文档版式视图点击宽度约束的。然后在身份检查的在用户定义运行属性,点击 + 键路径。变化的的keyPath 的到的标识的,改变的类型 布尔的到的字符串的,并设置 redBoxWidth

  1. Click on the width constraint in the Document Layout View. Then in the Identity Inspector under User Defined Runtime Attributes, click on the + under Key Path. Change keyPath to identifier, change the Type Boolean to String, and set the Value to redBoxWidth.

然后在 viewDidLoad中可以通过名字来查找约束并改变它的值:

Then in ViewDidLoad it is possible to find the constraint by name and change its value:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        for subview in view.subviews as [UIView] {
            for constraint in subview.constraints() as [NSLayoutConstraint] {
                if constraint.identifier == "redBoxWidth" {
                    constraint.constant = 300
                }
            }
        }
    }
}


这篇关于有没有一种方法,以一个标识符在Interface Builder添加到自动布局限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:12