本文參考了史上最全的iOS之UITextView實作placeHolder占位文字的N種方法,從中選出了我認為最省事的一種方法,盡量最簡化,代碼如下:
class CustomTextView: UITextView {
private var _placeholder:String!
init(frame:CGRect,placeholder:String) {
super.init(frame: frame, textContainer: nil)
_placeholder = placeholder
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: .UITextViewTextDidChange, object: self)//觀察是否有文字輸入
}
//無論我們想要繪制什麼圖形,首要任務就是先擷取上下文,你可以把上下文了解成一塊畫布,有了畫布才能畫東西;iOS 有三種擷取上下文的方式:重寫 UIView 的drawRect 和 drawRect inContext 方法會自動生成一個上下文,我們直接在這兩個方法裡繪制内容,UIView 就能自動渲染出來了,還有一種方法是使用UIGraphicsBeginImageContextWithOptions方法自己建立一個 UIImage 類型的上下文,然後使用let ctx = UIGraphicsGetCurrentContext() 擷取就行了
override func draw(_ rect: CGRect) {
if hasText{
return//如果輸入框内有文字,直接傳回
}
_placeholder.draw(in: CGRect(x:,y:,width:rect.width-,height:rect.height), withAttributes: [NSForegroundColorAttributeName:UIColor.yellow,NSFontAttributeName:UIFont.systemFont(ofSize: )])//占位符的位置坐标,字型大小以及繪制區域大小,如果你對占位符的大小和位置不滿意,請在這修改
}
func textDidChange(){
setNeedsDisplay()//調用drawRect方法,切勿手動調用drawRect方法
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
///////////////////////
override func viewDidLoad() {
super.viewDidLoad()
let textView = CustomTextView(frame: CGRect(x: , y: , width: , height: ),placeholder:"我是占位符")
textView.backgroundColor = UIColor.brown
view.addSubview(textView)
}

是不是狠簡單