UITextView自身没有提供Placeholder功能,需要使用者自行添加,这里利用@@IBInspectable @IBDesignable提供了方便的设置方法

基本功能实现

由于Extension/Category不允许存在Stored Properties,我们需要派生其子类

class PTextView: UITextView {
    //存储属性,存放placeHolder内容
    var placeHolder: String? = "" {
            //属性观察者
            didSet {
                if self.text == "" {
                    self.text = placeHolder
                    self.textColor = .lightGray
                }
            }
        }
    }

    //监听事件,根据文本框内容改变文字及颜色
    override func becomeFirstResponder() -> Bool {
        if self.text == placeHolder||self.text == "" {
            self.text = ""
            self.textColor = .black
        }
        return super.becomeFirstResponder()
    }
    
    override func resignFirstResponder() -> Bool {
        text = self.text.replacingOccurrences(of: " ", with: "")
        if text == "" {
            self.text = placeHolder
            self.textColor = .lightGray
        }
        return super.resignFirstResponder()
    }
}

在Interface Builder中使用

Xcode中可以通过@IBDesignable指定此类在IB中可以进行预览,@IBInspectable指定可以在Inspector中对标注的属性进行修改,使用方法如下

import UIKit

@IBDesignable
class PHTextView: UITextView {
    @IBInspectable var placeHolder: String? = "" {
        //观察者省略...
    }
    //监听事件省略...
}

clipboard.png


Hydrogen
2.5k 声望73 粉丝

Write code for fun.