[英]How to change aspect ratio of a UIView
我有一个自定义UIView,它以编程方式使用自动布局来设置框架的大小。 为此,我将视图的width属性的约束设置为等于超级视图的宽度,然后将宽高比的约束设置为某个硬编码值
//width constraint
NSLayoutConstraint *widhtConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:scrollView
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:8.0f];
[scrollView addConstraint:widhtConstraint];
//aspect ratio constraint
NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:entryView
attribute:NSLayoutAttributeHeight
multiplier:80.0/27.0//aspect ratio same as formula view
constant:0.0f];
[scrollView addConstraint:aspectRatioConstraint];
请参考图片:
我希望通过增加按钮的高度来更改该框架的宽高比(“查看更多”),然后在触摸同一按钮时将其调整为原始尺寸。此外,我如何计算所控制视图的总高度所有子视图,以使每个子视图都可见而不被裁剪。(基本上是标准折叠功能)
您可以在代码中将宽高比作为变量,并使用代码在诸如updateConstraints之类的方法中设置约束。
float aspectRatio; NSLayoutConstraint *aspectRatioConstraint=[NSLayoutConstraint constraintWithItem:entryView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:entryView
attribute:NSLayoutAttributeHeight
multiplier:self.aspectRatio//aspect ratio same as formula view
constant:0.0f];
然后,当按下按钮时,可以在action方法中将self.aspectRatio修改为合适,然后调用setNeedsUpdateConstraints和随后的setNeedsLayout。
我还不清楚问题到底是什么,但是可以通过更改按钮的约束来扩展/折叠超级视图,这很容易:
如果这是您追求的目标,则可以在此处找到可下载的示例项目: https : //github.com/mattneub/Programming-iOS-Book-Examples/tree/master/bk2ch04p183animationAndAutolayout4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.