天天看点

自定义的TextView,带有placeholder

最近写项目总是用到textView,无奈系统textView控件不像textField一样有占位符,所以只好自己自定义了一个带有占位符的textView,可以在storyboard中显示占位符属性,希望可以帮到大家!(swift)

@IBDesignable class JHTextView: UIView , UITextViewDelegate {

    @IBOutlet var contentView: UIView!
    @IBOutlet var textView: UITextView!
    /** 占位文字label */
    @IBOutlet private var placeholderLabel: UILabel!
    /** 占位文字 */
    @IBInspectable var placeholder : String? {
        get {
            return placeholderLabel.text
        }
        set {
            self.placeholderLabel.text = newValue
        }
    }
    /** 占位文字 颜色 */
    @IBInspectable var placeholderColor : UIColor = UIColor.lightGrayColor() {
        didSet {
            self.placeholderLabel.textColor = placeholderColor
        }
    }
    /** 占位文字 字体大小 */
    @IBInspectable var placeholderFont : CGFloat =  {
        didSet {
            self.placeholderLabel.font = UIFont.systemFontOfSize(placeholderFont)
        }
    }

    func loadViewFfromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: String(self.dynamicType), bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[] as! UIView
        self.textView.delegate = self
        return view
    }

    func setupSubviews() {
        contentView = loadViewFfromNib()
        contentView.frame = bounds
        addSubview(contentView)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }
    /** UITextViewDelegate */
    func textViewDidBeginEditing(textView: UITextView) {
        self.placeholderLabel.hidden = true
    }

    func textViewDidEndEditing(textView: UITextView) {
        self.placeholderLabel.hidden = textView.text != ""
    }


}
           

在storyboard中只需要创建一个view与其关联,就能自定义textView的placeholder文字,可以修改文字大小和颜色

文件下载