Swift 实现UITextView PlaceHolder简易版

  1. 优点,简单易用。
  2. 缺点,未经测试。不能再次使用代理,需要自己添加回调函数实现。
extension UITextView: UITextViewDelegate {
    
    var xColor: (textColor: UIColor, placeHolderColor: UIColor)? {
        set {
            textColor = newValue?.placeHolderColor
            objc_setAssociatedObject(self, UnsafeRawPointer(bitPattern: #function.hashValue)!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            let obj: (UIColor, UIColor)? = objc_getAssociatedObject(self, UnsafeRawPointer(bitPattern: #function.hashValue)!) as? (UIColor, UIColor)
            return obj
        }
    }
    
    var placeHolder: String? {
        set {
            delegate = self
            text = newValue
            objc_setAssociatedObject(self, UnsafeRawPointer(bitPattern: #function.hashValue)!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        get {
            let obj: String? = objc_getAssociatedObject(self, UnsafeRawPointer(bitPattern: #function.hashValue)!) as? String
            return obj ?? ""
        }
    }
    
    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if textView.text == placeHolder {
            textView.text = ""
            textView.textColor = xColor?.textColor
        }
        return true
    }
    
    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        if textView.text == "" {
            textView.text = placeHolder
            textView.textColor = xColor?.placeHolderColor
        }
        return true
    }

}

你可能感兴趣的:(Swift 实现UITextView PlaceHolder简易版)