如何在iOS8中更改NSLayoutConstraint的'mutiplier' 属性的值

How to change the value of 'mutiplier' property of NSLayoutConstarint in iOS8

我使用自适应布局功能来设计应用程序。我采用 "Aspect Ratio" 约束的 IBOutlet。我想将此 Aspect Ratio Value 的值更改为当前值的两倍。问题是“constraint”属性 可以通过代码轻松设置,但是“multiplier”属性 是只读的属性。对于纵横比更改,需要更改 "multipier" 值。我该怎么做?

@property (retain, nonatomic) IBOutlet NSLayoutConstraint *leftImageWidthAspectRatio;

在代码中

NSLog(@"cell.leftImageWidthAspectRatio:%@ : %lf  %lf",cell.leftImageWidthAspectRatio, cell.leftImageWidthAspectRatio.constant,cell.leftImageWidthAspectRatio.multiplier);

结果

 cell.leftImageWidthAspectRatio:<NSLayoutConstraint:0x7c9f2ed0 UIView:0x7c9f2030.width == 2*RIFeedThumbImageView:0x7c9f2c90.width> : 0.000000  2.000000

这个问题的一个简单的解决方案,我找到了

  1. 对宽度进行另一个约束
  2. 更改纵横比的优先级(小于宽度约束优先级);
  3. 借助纵横比更改宽度约束值multipile 属性

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

@property (retain, nonatomic) IBOutlet NSLayoutConstraint *leftImageWidthAspectRatio;

在代码中

cell.leftImageWidthAspectRatio.priority=500;
    cell.leftImagewidthConstaint.constant =cell.leftImagewidthConstaint.constant*cell.leftImageWidthAspectRatio.multiplier;

这成功了

你是对的——不支持更改现有约束的乘数。 constant 是例外,不是规则。来自 docs:

Unlike the other properties, the constant can be modified after constraint creation. Setting the constant on an existing constraint performs much better than removing the constraint and adding a new one that's exactly like the old except that it has a different constant.

您需要做的就是最后所描述的:用相同但具有不同乘数的约束替换现有约束。这样的事情应该有效:

NSLayoutConstraint *oldConstraint = cell.leftImageWidthAspectRatio;
CGFloat newMultiplier = 4; // or whatever
NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:oldConstraint.firstItem attribute:oldConstraint.firstAttribute relatedBy:oldConstraint.relation toItem:oldConstraint.secondItem attribute:oldConstraint.secondAttribute multiplier:newMultiplier constant:oldConstraint.constant];
newConstraint.priority = oldConstraint.priority;
[cell removeConstraint:oldConstraint];
[cell addConstraint:newConstraint];

请注意,cell 可能是错误的观点——这取决于 IB 决定将原始约束放置在何处。如果这不起作用,请深入了解受约束视图的超视图(您可以检查它们对 constraints 属性 有哪些约束),直到找到它的结束位置。