ios - 动态更改由自动布局控制的 View 的纵横比

标签 ios objective-c macos autolayout nslayoutconstraint

问题

在 UI 中,我有一些观点认为哪些内容是可拉伸(stretch)的,但应该保留一些纵横比。此宽高比在运行时会发生变化,并且当某些描述宽高比的属性发生变化时,应更新 View 布局。

我已经公开了 NSLayoutConstraint,但是它用于纵横比的属性:multiplier 是只读的。更有趣的是类似的属性 constant 可以改变。

可能的解决方案

  1. 我可以只使用固定宽度或高度的约束并根据预期比率计算它,但这需要额外的样板代码,这些代码将对几何/布局变化使用react,我宁愿避免这种情况。
  2. 我可以尝试使用 intrisicContentSizesizeThatFits: 但我不确定如何将其与 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/

相关文章:

ios - CALayer 圆形蒙版动画不正确的行为 + Swift

iphone - Facebook iOS SDK 3.1 在 friend 墙上发布图片错误

java - 我有一个相当于 Objective-C stringWithUTF8String :? 的 Java

c - 中止陷阱 : 6 in C Program

ios - 如何解决实现错误?

ios - 如何优化此图像处理用最接近的可用 RGB 替换图像上的所有像素?

ios - 使用 Core Graphics 绘制圆弧时绘制的额外线条

ios - UIScrollView 不适用于从选项卡栏 Controller 调用的自动布局

macos - brew install docker 不包括 docker 引擎?

swift - 从 Swift 异常生成错误表