オーバーフローをカットし、カウントラベルを更新しながら、最大文字数までコードを貼り付けることもできるようにしたい場合は、次のようにします。
let maxChar: Int
let countLabel: UILabel
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let oldChar = textView.text.count - range.length
let oldRemainingChar = maxChar - oldChar
let newChar = oldChar + text.count
let newRemainingChar = maxChar - newChar
let replaceChar = newRemainingChar > 0 ? text.count : oldRemainingChar
if
let textRange = textView.textRange(for: range),
replaceChar > 0 || range.length > 0
{
textView.replace(textRange, withText: String(text.prefix(replaceChar)))
countLabel.text = String(describing: maxChar - textView.text.count)
}
return false
}
拡張子付き:
extension UITextInput {
func textRange(for range: NSRange) -> UITextRange? {
var result: UITextRange?
if
let start = position(from: beginningOfDocument, offset: range.location),
let end = position(from: start, offset: range.length)
{
result = textRange(from: start, to: end)
}
return result
}
}