UITextView添加Placeholder(swift)

前端之家收集整理的这篇文章主要介绍了UITextView添加Placeholder(swift)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

UITextView添加Placeholder(swift)

by 伍雪颖

添加UILabel并初始化
publicletplaceholderLabel: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
}
原文链接:https://www.f2er.com/swift/327523.html

猜你在找的Swift相关文章