//
|
// YYTextView.swift
|
// OKProject
|
//
|
// Created by alvin_y on 2020/5/28.
|
// Copyright © 2020 yangwang. All rights reserved.
|
//
|
|
import Foundation
|
|
@IBDesignable class YYTextView: UITextView {
|
|
/// 占位字符串
|
@IBInspectable var placeholder: String = ""
|
|
/// 最大可输入字数
|
@IBInspectable var maximumLength: Int = 0
|
|
deinit {
|
NotificationCenter.default.removeObserver(self)
|
}
|
|
|
required init?(coder aDecoder: NSCoder) {
|
super.init(coder: aDecoder)
|
|
initialization()
|
}
|
|
override init(frame: CGRect, textContainer: NSTextContainer?) {
|
super.init(frame: frame, textContainer: textContainer)
|
|
initialization()
|
}
|
|
override func layoutSubviews() {
|
super.layoutSubviews()
|
|
setNeedsDisplay()
|
}
|
|
private func initialization() {
|
NotificationCenter.default.addObserver(self, selector: #selector(textViewTextDidChange(sender:)), name: UITextView.textDidChangeNotification, object: nil)
|
|
}
|
|
@objc private func textViewTextDidChange(sender: Notification) {
|
|
let string = text
|
let inputMode = textInputMode?.primaryLanguage; // 键盘输入模式
|
|
if (maximumLength > 0) {
|
|
if (inputMode == "zh-Hans") {
|
|
let selectedRange: UITextRange? = markedTextRange
|
|
if selectedRange == nil {
|
|
let substring = string!.prefix(maximumLength)
|
|
text = String(substring)
|
}
|
|
} else {
|
|
if string!.count > maximumLength {
|
|
let substring = string!.prefix(maximumLength)
|
text = String(substring)
|
}
|
}
|
}
|
|
setNeedsDisplay()
|
}
|
|
override func draw(_ rect: CGRect) {
|
|
guard !hasText else { return }
|
|
// 属性
|
let attributes: [NSAttributedString.Key : Any] = [.font: font!, .foregroundColor: UIColor.lightGray]
|
|
// 画文字
|
var aRect = CGRect.zero
|
aRect.origin.x = 5
|
aRect.origin.y = 8
|
aRect.size.width = rect.size.width - (2 * aRect.origin.x)
|
aRect.size.height = rect.size.height
|
|
let string = placeholder as NSString
|
|
string.draw(in: aRect, withAttributes: attributes)
|
|
}
|
}
|