xcode 有没有办法在 Interface Builder 中向 Auto Layout Constraints 添加标识符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27791597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:27:18  来源:igfitidea点击:

Is there a way to add an identifier to Auto Layout Constraints in Interface Builder?

iosxcodeautolayoutinterface-builder

提问by Martin Woolstenhulme

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?

在 Interface Builder 中做了一些视觉布局之后,我创建了一些我想在运行时访问的约束。有没有办法在 Interface Builder 中标记或识别约束,以便以后可以查找?

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 Languageand 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.

我想这样做的原因是我需要根据视觉指定的约束执行一些计算。我知道 Apple 提供了Visual Format Language,我可以在控制器中以编程方式指定约束。我宁愿不使用这种方法,所以我不会丢失 IB 的设计时反馈。

Edit

编辑

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

制作参考插座确实有效,但问题仍然存在。

回答by vacawama

Update:

更新:

As explained by Bart?omiej Semańczyk in his answer, there is now an Identifierfield visible in the Attributes Inspectorfor the NSLayoutConstraintmaking it unnecessary to expose this field yourself. Just select the constraint in the Document Outlineview or in the Storyboard view and then add an identifier in the Attributes Inspectoron the right.

正如巴特解释呢?omiejSemańczyk在他的回答,现在有一个标识符字段可见在属性检查器NSLayoutConstraint使其不必暴露自己这一领域。只需在Document Outline视图或 Storyboard 视图中选择约束,然后在右侧的Attributes Inspector 中添加一个标识符。



Earlier Answer:

之前的回答:

Yes, this can be done. NSLayoutConstrainthas a property called identifierthan can be exposed in Interface Builderand assigned. To demo this, I created a Single View Applicationthat 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 redBoxWidthby doing the following:

是的,这是可以做到的。 NSLayoutConstraint有一个属性identifier,可以在Interface Builder 中公开并分配。为了演示这个,我创建了一个单一视图应用程序,它有一个红色框的子视图。这个子视图有 4 个约束:宽度、高度、在容器中水平居中、在容器中垂直居中。我redBoxWidth通过执行以下操作为宽度约束提供了标识符:

  1. Click on the width constraint in the Document Layout View. Then in the Identity Inspectorunder User Defined Runtime Attributes, click on the +under Key Path. Change keyPathto identifier, change the TypeBooleanto String, and set the Valueto redBoxWidth.

    naming a constraint

  2. Then in ViewDidLoadit 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
                    }
                }
            }
        }
    }
    
  1. 单击文档布局视图中的宽度约束。然后在身份检查用户自定义属性运行,点击+下的关键路径。将keyPath更改为identifier,将Type Boolean更改为String,并将Value设置为redBoxWidth

    命名约束

  2. 然后ViewDidLoad可以通过名称找到约束并更改其值:

    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
                    }
                }
            }
        }
    }
    

回答by Bart?omiej Semańczyk

  1. Since Xcode 7 you can do it in storyboard:
  1. 从 Xcode 7 开始,您可以在故事板中进行操作:

enter image description here

在此处输入图片说明

  1. However if you set up your constraint in code, do the following:

    let constraint = NSLayoutConstraint() 
    constraint.identifier = "identifier"
    
  2. For these constraints you have set up in storyboard, but you must set identifier in code:

    for subview in view.subviews {
        for constraint in subview.constraints() {
            constraint.identifier = "identifier"
        }
    }
    
  1. 但是,如果您在代码中设置约束,请执行以下操作:

    let constraint = NSLayoutConstraint() 
    constraint.identifier = "identifier"
    
  2. 对于您在故事板中设置的这些约束,但您必须在代码中设置标识符:

    for subview in view.subviews {
        for constraint in subview.constraints() {
            constraint.identifier = "identifier"
        }
    }
    

回答by Volchik

Also you could link constraint to properties of your controller as you do for any other components. Just ctrl drag it into your code:

您也可以像对任何其他组件一样将约束链接到控制器的属性。只需 ctrl 将其拖入您的代码中:

enter image description here

在此处输入图片说明

And then it will be accessible in code of your controller as property:

然后它可以在您的控制器代码中作为属性访问:

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myConstraint;

And you could change it value for example:

您可以更改它的值,例如:

self.myConstraint.constant=100.;

回答by rebello95

Just adding on to @vacawama's answer. You can write a UIViewcategory and pull out constraints using a simple function, as opposed to copy/pasting loops everywhere you need to find a constraint:

只是添加到@vacawama 的答案。您可以UIView使用简单的函数编写类别并提取约束,而不是在需要查找约束的任何地方复制/粘贴循环:

.h file:

.h 文件:

#import <UIKit/UIKit.h>

@interface UIView (EasyAutolayout)

-(NSLayoutConstraint *)constraintForIdentifier:(NSString *)identifier;

@end

.m file:

.m 文件:

#import "UIView+EasyAutolayout.h"

@implementation UIView (EasyAutolayout)

-(NSLayoutConstraint *)constraintForIdentifier:(NSString *)identifier {

    for (NSLayoutConstraint *constraint in self.constraints) {
        if ([constraint.identifier isEqualToString:identifier]) {
            return constraint;
        }
    }
    return nil;
}

@end

回答by Henit Nathwani

Take the IBOutlet of your auto layout constraint.

获取自动布局约束的 IBOutlet。

There is one property called constantin the NSLayoutConstraintclass.

有一个称为一个属性不变NSLayoutConstraint类。

For eg, you've taken the IBOutlet of height constraint of any of the views from your IB, and you want to change it's height programmatically, all you need to do is:

例如,您已经从您的 IB 中获取了任何视图的高度约束的 IBOutlet,并且您想以编程方式更改它的高度,您需要做的就是:

 constraint.constant = isMoreHeight ? height1 : height2;

After doing this, you need to update all other views in the view hierarchy of the superview. To do this you'll need to write below line:

执行此操作后,您需要更新超级视图的视图层次结构中的所有其他视图。为此,您需要在以下行中写入:

[self setLayoutIfNeeded];

For better user experience, you can put this line inside your animations block for smoother transition effects,

为了更好的用户体验,您可以将此行放在动画块中以获得更平滑的过渡效果,

[UIView animateWithDuration:0.3f animations:^{
      [self.view layoutIfNeeded];
}];

Hope this helps..

希望这可以帮助..

回答by Carlos Carvalho

What about this:

那这个呢:

if let myconstraint = self.view.constraints.filter( { 
final private func getConstraintForButton(){
    let constraints  = self.myButton.constraints
    for constraint in constraints  {
        if constraint.identifier == "redBoxWidth" {
            constraint.constant = 300
            break
        }
    }
}
.identifier == "myconstraintId" }).first { // TODO: your code here... }

回答by ingconti

my two cents for OSX (previous answers deal with UIKit..)

我的 OSX 两分钱(以前的答案涉及 UIKit ..)

it work for OSX, too:

它也适用于 OSX:

##代码##

Note: seems NOT working on custom NSView, instead...

注意:似乎不适用于自定义 NSView,而是......