问题
在 UI 中,我有一些观点认为哪些内容是可拉伸(stretch)的,但应该保留一些纵横比。此宽高比在运行时会发生变化,并且当某些描述宽高比的属性发生变化时,应更新 View 布局。
我已经公开了 NSLayoutConstraint
,但是它用于纵横比的属性:multiplier
是只读的。更有趣的是类似的属性 constant
可以改变。
可能的解决方案
- 我可以只使用固定宽度或高度的约束并根据预期比率计算它,但这需要额外的样板代码,这些代码将对几何/布局变化使用react,我宁愿避免这种情况。
- 我可以尝试使用
intrisicContentSize
和sizeThatFits:
但我不确定如何将其与NSLayoutConstraint
一起使用
最佳答案
好吧,我提示太多了。删除和重新创建约束并不是什么大问题(感谢@vacawama):
- (void)updateASpectRatio: (float)aspectRatio {
// self.aspectRatioConstraint - has to be a strong reference
[self.aspectRatioView removeConstraint: self.aspectRatioConstraint];
self.aspectRatioConstraint = [NSLayoutConstraint constraintWithItem: self.aspectRatioConstraint.firstItem
attribute: self.aspectRatioConstraint.firstAttribute
relatedBy: self.aspectRatioConstraint.relation
toItem: self.aspectRatioConstraint.secondItem
attribute: self.aspectRatioConstraint.secondAttribute
multiplier: self.aspectRatioView.aspectRatio
constant: 0.0];
[self.aspectRatioView addConstraint: self.aspectRatioConstraint];
}
关于ios - 动态更改由自动布局控制的 View 的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209797/