【发布时间】:2020-01-16 10:34:20
【问题描述】:
在 SwiftUI 中将自定义 UILabel 添加到 List 时,单元格重用出现错误,其中某些单元格上的标签根本不可见,而在某些单元格上,它被放置在左上角没有任何考虑单元格的填充。它总是在初始单元格上完美呈现。
使用ScrollView 时不会出现此问题。这是一个已知的错误吗?有没有好的解决方法?
GeometryReader { geometry in
List {
ForEach(self.testdata, id: \.self) { text in
Group {
AttributedLabel(attributedText: NSAttributedString(string: text), maxWidth: geometry.size.width - 40)
}.padding(.vertical, 20)
}
}
}
struct AttributedLabel: UIViewRepresentable {
let attributedText: NSAttributedString
let maxWidth: CGFloat
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let label = UILabel()
label.preferredMaxLayoutWidth = maxWidth
label.attributedText = attributedText
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.backgroundColor = UIColor.red
return label
}
func updateUIView(_ label: UILabel, context: UIViewRepresentableContext<Self>) {}
}
【问题讨论】:
-
我在使用 UIViewRepresentable 中的 UILabel(呈现属性字符串)时遇到了看起来相同的问题。我只看到它发生在 List 中。
-
我遇到了完全相同的问题!
-
@Chris 你找到解决这个问题的方法了吗?我还试图通过 UIViewRepresentable 将 UIKit 中的自定义 UIView 放置在 SwiftUI 列表中。而且我不知道这个 UIKit 视图是布局的。我以为我不需要指定任何约束,它们只是在列表项的可用空间内调整大小