UITextView为空时仍占视图空间,UILabel却不占的技术求助
解决UITextView空文本时仍占用空间的问题
问题原因
- UILabel在文本设为
nil或空字符串时,会自动将自身的intrinsicContentSize(固有尺寸)缩为0,因此不会占据布局空间 - UITextView即使文本为空,默认仍会保留最小的固有尺寸(比如iOS中默认高度约30),再加上设置的背景色,就会出现空占位的情况
解决方法
方法1:直接控制显示/隐藏(最简单)
当不需要显示UITextView时,直接设置isHidden为true,和UILabel空文本的表现完全一致:
func changeText(str: String? = "", toggle: Bool) { alertTitle.text = toggle ? fullText: nil // 切换UITextView的隐藏状态 alertSubtitle.isHidden = toggle alertSubtitle.text = !toggle ? fullText : nil alertMessage.text = toggle ? fullText: nil }
方法2:自定义UITextView实现自动收缩
如果需要更灵活的场景(比如某些情况空文本要保留占位,某些情况不需要),可以自定义UITextView子类,重写固有尺寸:
class AutoCollapseTextView: UITextView { override var intrinsicContentSize: CGSize { // 文本为空时返回0高度,否则用默认固有尺寸 guard let text = self.text, !text.isEmpty else { return CGSize(width: UIView.noIntrinsicMetric, height: 0) } return super.intrinsicContentSize } override var text: String! { didSet { // 文本变化时通知布局更新 invalidateIntrinsicContentSize() } } }
之后把Storyboard中的UITextView类改为AutoCollapseTextView即可,空文本时会自动缩成0高度,不占空间。
方法3:通过约束动态调整高度
如果使用了高度约束,可以通过切换约束优先级来控制UITextView的高度:
- 给UITextView添加两个高度约束:一个正常高度(如200),优先级设为750;另一个高度0,优先级设为250
- 在
changeText函数中切换两者的优先级:
// 假设已关联两个约束:normalHeightConstraint、zeroHeightConstraint func changeText(str: String? = "", toggle: Bool) { alertTitle.text = toggle ? fullText: nil alertSubtitle.text = !toggle ? fullText : nil if toggle { normalHeightConstraint.priority = .defaultHigh zeroHeightConstraint.priority = .defaultLow } else { normalHeightConstraint.priority = .defaultLow zeroHeightConstraint.priority = .defaultHigh } view.layoutIfNeeded() alertMessage.text = toggle ? fullText: nil }
内容的提问来源于stack exchange,提问作者Beast
相关产品推荐
相关产品推荐

