標籤:ios
UITextView添加Placeholder(swift)by 伍雪穎
添加UILabel並初始化
public let placeholderLabel: UILabel = UILabel()
@IBInspectable publicvar placeholder: String ="" {
didSet {
placeholderLabel.text =placeholder
}
}
@IBInspectable publicvar placeholderColor: UIColor =UIColor(red: 0.0, green:0.0, blue: 0.0980392, alpha:0.22) {
didSet {
placeholderLabel.textColor =placeholderColor
}
}
override publicvar font: UIFont! {
didSet {
placeholderLabel.font =font
}
}
override publicvar textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment =textAlignment
}
}
addSubview添加上去
override init(frame:CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required publicinit(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 publicvar text: String! {
didSet {
textDidChange()
}
}
func textDidChange() {
placeholderLabel.hidden = !text.isEmpty
}
UITextView添加Placeholder(swift)