class PlaceStrTextView: UIView,UITextViewDelegate{ var palceStr = "即将输入的信息" //站位文字
var inputStr = "" //输入的信息 //创建一个textView
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()
} //添加textView
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滞空并将颜色改为黑色
textView.text = ""
}
textView.textColor = UIColor.black
} func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == "" {//如果用户没有输入任何信息就显示站位字符串
textView.text = palceStr
textView.textColor = UIColor.gray
}else{//一旦输入了信息你则颜色变成黑色
textView.textColor = UIColor.black
}
} func hiddenKeyBoard(){
(UIApplication.shared.delegate as! AppDelegate).window?.endEditing(true)
inputStr = textView.text
} }
//调用示例
@IBOutlet weak var textView: PlaceStrTextView! override func viewDidLoad() {
super.viewDidLoad() // Do any additional setup after loading the view.
textView.palceStr = "埃及的妇女节阿萨德来看风景安东尼设计开发"
textView.overrideSelf(frame: textView.frame)
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} @IBAction func tapAction(_ sender: Any) {
textView.hiddenKeyBoard()
print(textView.inputStr)
}