键盘

swift 重写带占位符的textView

2017-03-24  本文已影响222人  mapg
1.png 2.png 3.png
//简单使用
@IBOutlet weak var feedbackTV: PlaceholderTextView!
feedbackTV.overrideSelf(frame: feedbackTV.frame)
feedbackTV.palceStr = feedbackStr


 @IBAction func commitFeedbackAction(_ sender: Any) {
        feedbackTV.hiddenKeyBoard()
        if feedbackTV.inputStr == "" {
            self.showHint("您没有输入任何信息")
            return
        }
        
        if feedbackTV.inputStr == feedbackStr {
            self.showHint("您没有输入任何信息")
            return
        }
  }

import UIKit

typealias PlaceholderTextViewBlock = (_ inputStr:String) -> Void

class PlaceholderTextView: UIView,UITextViewDelegate{
    var pblock:PlaceholderTextViewBlock?
    func backInpuStr(block:@escaping PlaceholderTextViewBlock){
       pblock = block
    }
    //站位信息
    @IBInspectable var palceStr:String = ""{
        didSet{
           self.textView.text = self.palceStr
           self.textView.textColor = UIColor.gray
        }
    }

    var inputStr = "" //输入的信息
    
    lazy var textView:UITextView = {
        let tv = UITextView()
        tv.delegate = self
        tv.text = self.palceStr
        tv.textColor = UIColor.gray
        tv.backgroundColor = UIColor.clear
        tv.font = UIFont.systemFont(ofSize: 15)
        return tv
    }()
    
    func overrideSelf(frame: CGRect) {
        self.frame = frame
        addTextView()
    }
    
    func addTextView(){
        self.textView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        self.addSubview(self.textView)
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == palceStr {
            textView.text = ""
        }
        textView.textColor = UIColor.black
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        //如果为空或者输入的信息与站位信息一样
        inputStr = textView.text
        if textView.text == "" || textView.text == palceStr {
            textView.text = palceStr
            textView.textColor = UIColor.gray
        }else{
            textView.textColor = UIColor.black
        }
        if let block = pblock {
            block(inputStr)
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读