这是我的初始代码
import SwiftUI
struct Question01: View {
@State private var height: CGFloat = 0
var body: some View {
ScrollView(Axis.Set.vertical, showsIndicators: false) {
LazyVStack
{
ForEach(0..<100) { _ in
GridentLabel(fontSize: 14, fontColor: UIColor.red, transfromColor: UIColor.black, content: "ttttttttttttttttttttbbbbbbbbbbbbbbbbbtttttttttttttttttttttttttt", transfromContent: "bbbbbbbbbbbbbbbbb", labelHeight: $height)
.frame(height: height)
}
}
}
}
}
struct Question01_Previews: PreviewProvider {
static var previews: some View {
Question01()
}
}
struct GridentLabel: UIViewRepresentable {
let fontSize: CGFloat
let fontColor: UIColor
let transfromColor: UIColor
let content: String
let transfromContent: String
@Binding var labelHeight: CGFloat
func makeUIView(context: Context) -> UILabel {
let label = UILabel(frame: .zero)
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
if content.isEmpty == false {
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = 5.0
paragraph.lineBreakMode = NSLineBreakMode.byCharWrapping
let attrString = NSMutableAttributedString(string: content, attributes: [.paragraphStyle : paragraph, .font: UIFont.systemFont(ofSize: fontSize, weight: .regular), .foregroundColor: fontColor])
let range: NSRange = (content as NSString).range(of: transfromContent)
attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: transfromColor, range: range)
uiView.attributedText = attrString
DispatchQueue.main.async {
labelHeight = uiView.sizeThatFits(CGSize(width: uiView.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
}
}
}
}
为什么使用 LazyVstack 集合框架会导致死循环?我仍然无法理解这样的问题。如果直接使用Vstack,不会出现死循环。为什么,或者如果你不设置框架,它不会导致无限循环。虽然不设置框架不会对程序产生任何影响,但为什么会这样呢?