2

I use Adaptive layout features for designing an app. I take a IBOutlet of an "Aspect Ratio" constraint . I want to change the value of this Aspect Ratio Value to the double of current value. The problem is that "constraint" property can be set easily from Code, but "multiplier" property is read only property. For Aspect Ratio Change, "multipier" value change is necessary . How Could I do this?.

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

In code

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

Results that

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

2 回答 2

4

您是对的 - 不支持更改现有约束的乘数。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属性的约束),直到找到它的结束位置。

于 2015-06-04T05:16:32.010 回答
-1

这个问题的简单解决方案,我发现这样

  1. 为 Width 设置另一个约束
  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;

这工作成功

于 2015-06-04T04:59:47.043 回答