使用故事板中的标识符集来获取对NSLayoutConstraint的引用 [英] Get reference to NSLayoutConstraint using Identifier set in storyboard

查看:258
本文介绍了使用故事板中的标识符集来获取对NSLayoutConstraint的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用故事板设置了按钮的约束。我在约束的属性中看到了一个选项标识符。





我想引用这个约束,在代码中更改其值,以移动对象。



如何从此标识符中获取对此 NSLayoutContraint 的引用。



我阅读文档,它是这样写的

  @interface NSLayoutConstraint(NSIdentifier)
/ *为了方便调试,通过设置其标识符来命名约束,将在约束的描述中打印。
系统保留以UI和NS开头的标识符。
* /
@property(nullable,copy)NSString * identifier NS_AVAILABLE_IOS(7_0);

@end

所以我意识到这是为了调试目的。



如果我想得到它并使用它怎么办?我看到了此链接,但没有给出满意的答案:如何获取NSLayoutConstraint的

我假设您已为该按钮设置了一个插口,因此您有一个可用的参考。因此,首先,从您的按钮检索视图的约束。然后循环遍历数组,并在每次迭代中将每个约束的identifer属性与您在Interface Builder中输入的值进行比较。看起来你是在Objective-C编码,所以Objective-C代码示例如下。将@标识符更改为您在Interface Builder中设置的任何值。

  NSArray * constraints = [button constraints]; 
int count = [constraints count];
int index = 0;
BOOL found = NO;

while(!found&& index< count){
NSLayoutConstraint * constraint = constraints [index];
if([constraint.identifier isEqualToString:@identifier]){
//保存对约束的引用
found = YES;
}

index ++;
}


I was setting the constraints of a button using a storyboard. I saw an option, "Identifier" in the constraint's properties.

I want to make a reference to this constraint, to change its value in code, to move an object.

How can I get a reference to this NSLayoutContraint from this Identifier.

I read the documentation, it was written like this

@interface NSLayoutConstraint (NSIdentifier)
/* For ease in debugging, name a constraint by setting its identifier, which will be printed in the constraint's description.
 Identifiers starting with UI and NS are reserved by the system.
 */
@property (nullable, copy) NSString *identifier NS_AVAILABLE_IOS(7_0);

@end

So I realized that it's for debugging purposes.

What if I want to get it and use it? I saw this link, but no satisfactory answer was given: How to get NSLayoutConstraint's identifier by Its pointer?

解决方案

I assume you have an outlet set up for the button so you have an available reference to it. So first, retrieve the view's constraints from your button. Then loop through the array and on each iteration compare the identifer property of each constraint with the value you entered in Interface Builder. Looks like you are coding in Objective-C, so Objective-C code sample is below. Change @"identifier" to whatever value you set in Interface Builder.

NSArray *constraints = [button constraints];
int count = [constraints count];
int index = 0;
BOOL found = NO;

while (!found && index < count) {
    NSLayoutConstraint *constraint = constraints[index];
    if ( [constraint.identifier isEqualToString:@"identifier"] ) {
        //save the reference to constraint
        found = YES;
    }

    index++;
}

这篇关于使用故事板中的标识符集来获取对NSLayoutConstraint的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆