You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何UILabel无法显示多行?已设置numberOfLines=0等属性

问题分析与解决方案

嘿,你的UILabel没法多行显示,主要是两个约束设置的问题,我帮你拆解一下:

1. ScrollView的底部约束完全错误

你这段代码里的scrollView底部约束写反了:

scrollView.bottomAnchor.constraint(equalTo: view.topAnchor).isActive = true

这相当于把scrollView的底部贴在视图的顶部,直接导致scrollView的高度变成0,内容根本没法正常展示。正确的写法应该是把scrollView的底部和view的底部对齐:

scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

2. UILabel缺少宽度限制

虽然你设置了numberOfLines=0和lineBreakMode=.byWordWrapping,但UILabel不知道自己的最大宽度应该是多少,它会默认把文本挤在一行里。你需要给Label添加宽度约束,比如让它的宽度和scrollView关联(左右留边距更美观):

lblTitle.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -20).isActive = true

或者如果需要固定宽度,也可以设置成固定值,比如equalToConstant: 300。

修正后的完整约束代码参考

// 修正ScrollView约束
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

scrollView.addSubview(lblTitle)
lblTitle.text="Testing testing testing testing testing testing testing testing testing testing"
lblTitle.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive=true
lblTitle.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
// 添加宽度约束
lblTitle.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -20).isActive = true

scrollView.addSubview(btnGetChoose)
btnGetChoose.heightAnchor.constraint(equalToConstant: 50).isActive=true
btnGetChoose.widthAnchor.constraint(equalToConstant: 150).isActive=true
btnGetChoose.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
btnGetChoose.topAnchor.constraint(equalTo: lblTitle.bottomAnchor, constant: 10).isActive=true

这样修改后,你的Label就能根据宽度自动换行,实现多行显示啦~

内容的提问来源于stack exchange,提问作者user2872856

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:39:01