Search code examples
swiftui-text

How can I limit maxSize of custom UIViewRepresentable UITextview in SwiftUI


Be associated with: Frame height problem with custom UIViewRepresentable UITextView in SwiftUI I limit the maxSize like:

    #Preview {
    VStack {
        AttributedText("long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text", HTMLFormatter())
            .frame(minHeight: 1, maxHeight: 100)
            .frame(height: 100)
    }
        .frame(maxHeight: 100)
        .background(Color.blue)
    }
    

And the heigt is large than 100. Can't fix it, Help me pls!


Solution

  • We can pass maxHeight to UIKit And limit the intrinsicContentSize!

            if isAutoLayoutHeight {
                let size = contentSize
                if size.height < 0 {
                    // 宽度不限制,高度用最小高度的设置或者不限制
                    return CGSize(width: -1, height: minHeight ?? -1)
                } else if let maxHeight = self.maxHeight, size.height > maxHeight {
                    return CGSize(width: size.width, height: maxHeight)
                }
                
                return size
            }
            return super.intrinsicContentSize
        }```