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
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容