iOS UITextView 屬性
有這樣一種需求,在UITextView的屬性里是沒(méi)有像UITextFiled一樣的占位文字的,那么要讓UITextView擁有占位文字,需要什么思路呢?
解決方案如下:
- 分析:如同UITextField一樣,當(dāng)沒(méi)有輸入時(shí)顯示占位文字,當(dāng)有輸入時(shí)隨即消失,當(dāng)輸入完再刪除時(shí),又立刻出現(xiàn)
- 由上分析,可以肯定,這個(gè)占位文字我選擇一個(gè)UILable控件,因?yàn)樗軌蝻@示文字,而且便于修改占位文字屬性
- 通過(guò)分析,用通知或者代理來(lái)監(jiān)聽(tīng)UITextView屬性的改變,這里我使用通知!
具體代碼如下:
Swift代碼
import UIKit
/// 文本視圖
public class TCComposeTextView: UITextView {
/// 占位標(biāo)簽
fileprivate lazy var placeholderLabel = UILabel()
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupUI()
setupInputAccessoryView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - 監(jiān)聽(tīng)方法
@objc fileprivate func textChanged() {
placeholderLabel.isHidden = self.hasText
}
@objc fileprivate func finishInput() {
self.resignFirstResponder()
}
}
fileprivate extension TCComposeTextView {
func setupUI() {
NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: .UITextViewTextDidChange, object: self)
placeholderLabel.text = "寫下點(diǎn)什么吧..."
placeholderLabel.font = self.font
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.frame.origin = CGPoint(x: 5, y: 8)
placeholderLabel.sizeToFit()
addSubview(placeholderLabel)
delegate = self
}
func setupInputAccessoryView() {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44.0))
let doneItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(finishInput))
let flexibleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [flexibleItem, doneItem]
self.inputAccessoryView = toolbar
}
}
// MARK: - UITextViewDelegate
extension TCComposeTextView: UITextViewDelegate {
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if range.location > 99 {
return false
} else {
return true
}
}
}
寫在最后
TCComposeTextView是繼承自UITextView的自定義子類,如果使用,直接創(chuàng)建復(fù)制粘貼即可。當(dāng)然有什么問(wèn)題,可以留言給我,O(∩_∩)O謝謝!