我在ViewController中有两个UITextView,我想限制用户可以在TextView中编辑的字符数。
我正在使用方法textView(_:shouldChangeTextIn:replacementText:)
协议UITextViewDelegate
已声明
两个UITextView都有一个插座
@IBOutlet weak var UITextView1: UITextView!
@IBOutlet weak var UITextView2: UITextView!
和代表团
override func viewDidLoad() {
super.viewDidLoad()
UITextView1.delegate = self
UITextView2.delegate = self
}
我尝试了不同的方法来使其同时适用于两个UITextView(使用函数两次或使用switch语句来调整参数)
实际上我下面的代码顺利通过了构建测试。
// maximise number of characters typed in UITextViews
func textView( _ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let UITextViewA = UITextView1 {
let TextView1MaxLengh = 10
let TextView1Num = (UITextViewA.text as NSString).replacingCharacters(in: range, with: text)
let numberOfChars = TextView1Num.count
let NumberCharsString = "- \(String(TextView1MaxLengh - numberOfChars)) -"
return numberOfChars < TextView1MaxLengh
}
if let UITextViewB = UITextView2 {
let TextView2MaxLengh = 20
let TextView2Num = (UITextViewB.text as NSString).replacingCharacters(in: range, with: text)
let numberOfChars2 = TextView2Num.count
let NumberCharsString2 = "- \(String(TextView2MaxLengh - numberOfChars2)) -"
return numberOfChars2 < TextView2MaxLengh
}
return true
}
当我运行该应用程序并编辑TextView1时,它可以正常工作,但是当我尝试编辑第二个应用程序时,该应用程序崩溃并显示以下消息:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
我很确定这与授权方面有关,但无法解决
预先感谢您的帮助