美文网首页
Swift 实现UITextView PlaceHolder简易

Swift 实现UITextView PlaceHolder简易

作者: Afer | 来源:发表于2017-12-08 11:01 被阅读14次
  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简易

      本文链接:https://www.haomeiwen.com/subject/qaxeixtx.html