3

I have UILabel and UIButton inside view which can have different size, and I want label to be hidden completely if it can't fit all the content within current frame using only AutoLayout. So basically I want it to follow it's intrinsic size, and if it shrink, it should shrink straight to zero without any middle width. Desired example:

example non-collapsed desired collapsed view

Instead, I'm having it shrinking and trying to display as much as possible:

enter image description here

Is it possible to do only using AutoLayout? If not, why?

I tried to add zero-width constraint on label and set it's priority to be less than compression resistance of the label, but this does not work. I thought that once Autolayout engine broke intristic size rule, mine zero-width will be followed, but it seems I'm missing something.

EDIT: I would accept to embed label in some UIView subclass that can check intristic sizes of subviews and do layout in code, but I'm searching for most clean solution in general.

You can check out xib source in this gist

4

2 回答 2

2

我目前的解决方案是将标签嵌入自定义UIView中,并在其布局期间直接检查尺寸是否小于内部尺寸:

@implementation AutocollapsibleView

- (void)layoutSubviews {
    UIView *subview = self.subviews.firstObject;
    if (self.bounds.size.width < subview.intrinsicContentSize.width) {
        subview.frame = CGRectZero;
    } else {
        [super layoutSubviews];
    }
}

@end

幸运的是它适用于IB_DESIGNABLEmarco,所以我立即在 Interface Builder 中看到了结果

于 2017-03-27T05:24:53.990 回答
1

我知道你解决了你的问题,但只是为了在自动布局上提供一点颜色:我有同样的要求来“折叠”一个不能满足其内在内容大小的视图,并尝试了相同的零宽度约束技术。Auto Layout 文档的这一部分描述了该技术的问题:

在解决了所需的约束之后,Auto Layout 会尝试按照优先级从高到低的顺序解决所有可选约束。如果它无法解决可选约束,它会尝试尽可能接近所需结果,然后继续下一个约束。

显然,自动布局宁愿接近满足约束也不愿满足较低优先级的约束。这对我来说有点奇怪,因为如果我想要一个宽度,>= 100那么不清楚 90 是否比 80“更好”。也就是说,我确信这样做会在绝大多数情况下产生更直观的行为。

不幸的是,这使得在无法满足较高优先级约束的情况下,无法使用较低优先级约束作为“回退”约束。我想Apple的观点是,较低优先级约束的唯一目的是在较高优先级约束导致布局受限时使布局更加具体。

于 2017-07-07T13:24:55.033 回答