5

我有这样的 UITextView 包装器,它可以工作,但是当我将它放在 List 行中时。我希望它自动调整大小,即在这种情况下具有与父级匹配的宽度 List Row VStack { },以及根据文本长度自动调整大小的高度。文本应该换行。现在它几乎可以工作了,但是像 URL 这样的较长文本超出了可用的行宽。

List {
VStack(alignment: .leading) {
     if self.hasNote {
        TextView(text: text)

     }
}
struct TextView: UIViewRepresentable {

    // MARK: - Properties
    let text: String

    init(text: String) {
        self.text = text
    }

    func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()
        //textView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        textView.backgroundColor = UIColor.clear
        textView.isScrollEnabled = false
        textView.attributedText = self.attributedText
        textView.textContainer.lineBreakMode = .byWordWrapping
        //textView.layoutIfNeeded()
        textView.sizeToFit()
        return textView
    }

}

更新

现在我有这样的东西,它确实适合父 SwiftUI 视图(列表中的行),但它不换行(或根据内容大小垂直拉伸。如果滚动它会正确换行文本。另外,如果我设置 .frame(height: 500 ) 我可以看到它包含文本。但它不能正确自动调整大小。

 func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()

        textView.backgroundColor = UIColor.clear
        textView.isScrollEnabled = false
        textView.isSelectable = true

        let linkAttrs : [NSAttributedString.Key : Any]  = [
            .foregroundColor: accentColor,
            .underlineColor: accentColor,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]

        textView.linkTextAttributes = linkAttrs
        textView.attributedText = self.attributedText
        textView.textContainer.lineBreakMode = .byWordWrapping

        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        textView.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
        textView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        textView.setContentHuggingPriority(.defaultLow, for: .vertical)
        textView.sizeToFit()

        return textView
    }
4

0 回答 0