UITextView添加Placeholder(swift)
by 伍雪颖
添加UILabel并初始化
public let placeholderLabel: UILabel = UILabel()
@IBInspectable public
var placeholder: String =
"" {
didSet {
placeholderLabel.text =
placeholder
}
}
@IBInspectable public
var placeholderColor: UIColor =
UIColor(red: 0.0, green:
0.0, blue: 0.0980392, alpha:
0.22) {
didSet {
placeholderLabel.textColor =
placeholderColor
}
}
override public
var font: UIFont! {
didSet {
placeholderLabel.font =
font
}
}
override public
var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment =
textAlignment
}
}
addSubview添加上去
override init(frame:
CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public
init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "textDidChange",
name: UITextViewTextDidChangeNotification,
object: nil)
placeholderLabel.font =
font
placeholderLabel.textColor =
placeholderColor
placeholderLabel.textAlignment =
textAlignment
placeholderLabel.text =
placeholder
placeholderLabel.numberOfLines =
0
placeholderLabel.backgroundColor =
UIColor.clearColor()
placeholderLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
addSubview(placeholderLabel)
}
输入文字消失的事件
override public
var text: String! {
didSet {
textDidChange()
}
}
func textDidChange() {
placeholderLabel.hidden = !text.isEmpty
}