swift UITextView/YYTextView 自适应文字高度方案

子类化一个TextView,重写UITextView的contentSize属性的setter和intrinsicContentSize 的getter;
由于swift不能像Objective-C那样直接重写属性的setter和getter方法,swift采用重写属性的方案,通过重写属性来实现重写setter或getter方法

例如
HeightAdaptedTextView可以指定自适应最小或最大内容高度

class HeightAdaptedTextView: YYTextView {
    
    var minHeight: CGFloat
    
    var maxHeight: CGFloat
    
    init(minHeight:CGFloat = 0.0 ,maxHeight:CGFloat = 0.0,frame:CGRect = .zero) {
        self.minHeight = minHeight
        self.maxHeight = maxHeight
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var contentSize: CGSize {
        get {
            return super.contentSize
        }
        
        set {
            invalidateIntrinsicContentSize() // 失效固有的contentSize
            super.contentSize = newValue
        }
    }
    
    // 重写固有的contenSize
    override var intrinsicContentSize:CGSize {
        get {
            if (minHeight > 0 &&
                self.contentSize.height > 0 &&
                self.contentSize.height <= minHeight) {
                return CGSize.init(width: self.contentSize.width, height: minHeight)
            }
            
            if (maxHeight > 0 &&
                self.contentSize.height > 0 &&
                self.contentSize.height >= maxHeight) {
                return CGSize.init(width: self.contentSize.width, height: maxHeight)
            }
            
            return self.contentSize
        }
        
    }
}

使用HeightAdaptedTextView 例子为:

   lazy var contentTextView: HeightAdaptedTextView = {
        let textView = HeightAdaptedTextView(minHeight: 40)
        textView.isEditable = false
        textView.isScrollEnabled = false
        
        return textView
    }()

你可能感兴趣的:(swift UITextView/YYTextView 自适应文字高度方案)