26
2017
09

UITextView的PlaceholderTextView封装Swift4.0

在开发中根据业务逻辑的需求我们需要封装很多控件来提高开发效率,开发效果

import UIKit

class PlaceholderTextView: UITextView , UITextViewDelegate{

    var placeholder : String?
    var placeholderFont : UIFont?
    var placeholderColor : UIColor?


    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        self.addSubview(placeholderLabel)

        NotificationCenter.default.addObserver(self, selector: #selector(textDidBeginEditing), name: NSNotification.Name.UITextViewTextDidBeginEditing, object: nil)

        //文本框编辑结束时,触发
        NotificationCenter.default.addObserver(self, selector: #selector(textDidEndEditing), name: NSNotification.Name.UITextViewTextDidEndEditing, object: nil)


        //文本框内容改变时,触发
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)


        if placeholder == nil{

            placeholder = "请输入内容"

        }

        if placeholderFont == nil {

            placeholderFont = UIFont.systemFont(ofSize: 16)

        }

        if placeholderColor == nil {

            placeholderColor = UIColorFromRGB(rgbValue: 0xa0a0a0)

        }


        let fontSize = CGSize(width: self.width - 16, height: self.height - 10)

        let placeSize:CGSize = placeholder!.boundingRect(with: fontSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: placeholderFont!], context: nil).size;


        placeholderLabel.frame = CGRect(x:8, y:5, width:placeSize.width ,height:placeSize.height + 1)
        placeholderLabel.text = placeholder!
        placeholderLabel.font = placeholderFont!
        placeholderLabel.textColor = placeholderColor!


    }

  @objc  func textDidBeginEditing(){

      //print("textDidBeginEditing")

    }

    @objc func textDidEndEditing(){
        //print("textDidEndEditing")
    }


    @objc func textDidChange(){

        if self.text.isEmpty {

            placeholderLabel.isHidden = false
        }else{
            placeholderLabel.isHidden = true
        }

    }


    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

    }



    lazy var  placeholderLabel:UILabel = {
        let placeholderLabel = UILabel()
        placeholderLabel.numberOfLines = 0
        return placeholderLabel
    }()

    /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */

}
上一篇:Xcode删除多余的模拟器 下一篇:react native学习笔记10——react-navigation的嵌套使用