iOS NSLayoutConstraint使用constraintWithItem修复宽度 [英] iOS NSLayoutConstraint Fixed Width using constraintWithItem
问题描述
我想设置一个约束,以编程方式为UIButton提供固定(常量)宽度。我知道我可以使用constraintsWithVisualFormat来做到这一点,但我一直在使用constraintWithItem来解决代码中的所有约束。如果有任何方法可以使用constraintWithItem,我想知道好奇/一致性。
I'd like to set a constraint to give a UIButton a fixed (constant) width programmatically. I know I can do this with constraintsWithVisualFormat, but I've been using constraintWithItem for all of my constraints in code. I was wondering for the sake of curiosity/consistency if there was any way to do this with constraintWithItem.
推荐答案
找到我的解决方案。只需将另一个对象设置为nil,将另一个属性设置为NSLayoutAttributeNotAnAttribute(这是我没想到的)并使用常量参数作为固定宽度:
Found my solution. Just set the other object to nil, and the other attribute to NSLayoutAttributeNotAnAttribute (this was what I failed to think of) and use the constant parameter for the fixed width:
[self addConstraint:[NSLayoutConstraint constraintWithItem:myButton
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:200]];
编辑:因为这个答案似乎仍然得到了相当多的观点,我想我会添加Swift语法:
since this answer still seems to get a fair share of views, I thought I'd add the Swift syntax:
self.addConstraint(NSLayoutConstraint(
item: myButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 200))
这篇关于iOS NSLayoutConstraint使用constraintWithItem修复宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!