gpt4 book ai didi

iOS 自动布局 : Issue with UILabels in a resizing parent view

转载 作者:IT王子 更新时间:2023-10-29 07:48:16 26 4
gpt4 key购买 nike

我有一个只包含 UILabel 的 View 。此标签包含多行文本。父级具有可变宽度,可以使用平移手势调整大小。我的问题是,当我这样做时,调整 UILabel 的大小时不会重新计算其高度,以便所有内容仍然可见,它只是将其切断。

我已经设法用一些 hack 修复了它,但它运行起来非常慢:

- (void)layoutSubviews {

CGSize labelSize = [self.labelDescription sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

if (self.constraintHeight) {
[self removeConstraint:self.constraintHeight];
}

self.constraintHeight = [NSLayoutConstraint constraintWithItem:self.labelDescription attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:labelSize.height];

[self addConstraint:self.constraintHeight];

[super layoutSubviews];
}

这不应该通过自动布局自动发生吗?

编辑

我的观点的结构是:

UIScrollView
---> UIView
---> UILabel

以下是 UIScrollView 的约束:

<NSLayoutConstraint:0x120c4860 H:|-(>=32)-[DescriptionView:0x85c81c0]   (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c48a0 H:|-(32@900)-[DescriptionView:0x85c81c0] priority:900 (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c48e0 H:[DescriptionView:0x85c81c0(<=576)]>,
<NSLayoutConstraint:0x120c4920 H:[DescriptionView:0x85c81c0]-(>=32)-| (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c4960 H:[DescriptionView:0x85c81c0]-(32@900)-| priority:900 (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x8301450 DescriptionView:0x85c81c0.centerX == UIScrollView:0x85db650.centerX>,

以下是 UIView 的约束:

<NSLayoutConstraint:0x85c4580 V:|-(0)-[UILabel:0x85bc7b0]   (Names: '|':DescriptionView:0x85c81c0 )>,
<NSLayoutConstraint:0x85c45c0 H:|-(0)-[UILabel:0x85bc7b0] (Names: '|':DescriptionView:0x85c81c0 )>,
<NSLayoutConstraint:0x85c9f80 UILabel:0x85bc7b0.trailing == DescriptionView:0x85c81c0.trailing>,
<NSLayoutConstraint:0x85c9fc0 UILabel:0x85bc7b0.centerY == DescriptionView:0x85c81c0.centerY>

UILabel 本身没有任何限制,除了将其固定到其父级的边缘

最佳答案

好吧,我终于成功了。解决方案是在 viewDidLayoutSubviews 中设置 preferredMaxLayoutWidth,但仅在第一轮布局之后。您可以通过异步分派(dispatch)回主线程来简单地安排它。所以:

- (void)viewDidLayoutSubviews {
dispatch_async(dispatch_get_main_queue(), ^{
self.theLabel.preferredMaxLayoutWidth = self.theLabel.bounds.size.width;
});
}

这样,您就不会设置 preferredMaxLayoutWidth,直到 标签的宽度已由其父 View 相关的约束正确设置。

此处的工作示例项目:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/ch23p673selfSizingLabel4/p565p579selfSizingLabel/ViewController.m

编辑:另一种方法!子类化 UILabel 并覆盖 layoutSubviews:

- (void) layoutSubviews {
[super layoutSubviews];
self.preferredMaxLayoutWidth = self.bounds.size.width;
}

结果是一个自动调整大小的标签 - 它会自动更改其高度以适应其内容,无论其宽度如何变化(假设其宽度因约束/布局而改变)。

关于iOS 自动布局 : Issue with UILabels in a resizing parent view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com