all*_*tom 14 uilabel swift swiftui
将 lineBreakMode 设置为 byWordWrapping 并将 numberOfLines 设置为 0 似乎还不够:
struct MyTextView: UIViewRepresentable {
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.text = "Here's a lot of text for you to display. It won't fit on the screen."
return label
}
func updateUIView(_ view: UILabel, context: Context) {
}
}
struct MyTextView_Previews: PreviewProvider {
static var previews: some View {
MyTextView()
.previewLayout(.fixed(width: 300, height: 200))
}
}
Run Code Online (Sandbox Code Playgroud)
无论我对 lineBreakMode 使用哪种设置,文本都不会换行。画布预览和实时预览都如下所示:
我得到的最接近的是设置 preferredMaxLayoutWidth,这确实会导致文本换行,但似乎没有一个值表示“无论视图大小如何”。
LuL*_*aGa 16
可能的解决方案是将宽度声明为 MyTextView 上的变量:
struct MyTextView: UIViewRepresentable {
var width: CGFloat
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.preferredMaxLayoutWidth = width
label.text = "Here's a lot of text for you to display. It won't fit on the screen."
return label
}
func updateUIView(_ view: UILabel, context: Context) {
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用 GeometryReader 找出有多少可用空间并将其传递给初始化器:
struct ExampleView: View {
var body: some View {
GeometryReader { geometry in
MyTextView(width: geometry.size.width)
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*bro 11
Try to use this magic line in makeUIView() func
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4658 次 |
| 最近记录: |