文章目录
- 截图
- 代码:具体使用
- 代码:CustomTextView
截图
代码:具体使用
scrollView.addSubview(contentTextView)
contentTextView.placeholderLabel.text = LocalizableManager.localValue("write_comment")
contentTextView.maxCharacters = 500
contentTextView.backgroundColor = newUIBackColor
contentTextView.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(20)
make.top.equalTo(problemLabel.snp_bottomMargin).offset(20)
make.height.equalTo(150)
}
contentTextView.characterCountChanged = { [self] count in
print("当前输入了 \(count) 个字符")
textCountLabel.text = String(count) + "/500"
}
代码:CustomTextView
class CustomTextView: UITextView {
var placeholderLabel: UILabel!
var maxCharacters = 200
var characterCountChanged: ((Int) -> Void)?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
delegate = self
self.font = UIFont.systemFont(ofSize: 15)
placeholderLabel = UILabel()
placeholderLabel.text = LocalizableManager.localValue("report_description_tips")
placeholderLabel.font = self.font
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.numberOfLines = 0
placeholderLabel.isHidden = !self.text.isEmpty
addSubview(placeholderLabel)
updatePlaceholderFrame()
}
override func layoutSubviews() {
super.layoutSubviews()
updatePlaceholderFrame() }
private func updatePlaceholderFrame() {
let placeholderSize = placeholderLabel.sizeThatFits(CGSize(width: self.frame.width - 10, height: CGFloat.greatestFiniteMagnitude))
placeholderLabel.frame = CGRect(x: 5, y: 5, width: placeholderSize.width, height: placeholderSize.height)
}
}
extension CustomTextView: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = !textView.text.isEmpty
if textView.text.count > maxCharacters {
textView.text = String(textView.text.prefix(maxCharacters))
}
characterCountChanged?(textView.text.count)
}
}