我正在开发一个包含textView和一些按钮的应用程序,它会根据光标位置进行一些计算。它包含for循环和数组,以及一个String扩展名,用于在curser之后/之前获取字符并对其进行添加或删除。它可以在不超过500个字符的情况下平稳运行,但是超过1000个字符时,它开始变得缓慢,难以在textView中添加或从textView中删除,并且无法使用。我已经在iPhone 6s Plus和iPad Pro 2nd 12inch上对其进行了测试,并且在Xcode模拟器中,所有这些设计的行为都完全相同,因此我认为这不是硬件限制。
下面是一些代码示例:
func checkLetter () {
let nextOne = textView.text.unicodeScalars[getCursorPosition()]
let nextTwo = textView.text.unicodeScalars[getCursorPosition()+1]
let nextThree = textView.text.unicodeScalars[getCursorPosition()+2]
let testLetter = ["ّ","ْ","ٌ","ُ","ٍ","ِ","ً","َ"]
for b in 0...7 {
if nextThree == testLetter[b] && nextTwo == "ّ" {
print ("Next Three!")
nextChar()
nextChar()
delLetter()
delLetter()
preChar()
}else if nextThree == testLetter[b] && nextTwo == testLetter[b] {
print ("Next Three!")
nextChar()
nextChar()
nextChar()
delLetter()
delLetter()
preChar()
}else if nextTwo == testLetter[b] {
print ("Next Two!")
nextChar()
nextChar()
delLetter()
preChar()
}else if nextOne == testLetter[b] {
print ("Next One!")
nextChar()
delLetter()
preChar()
}
}
}
。
func preChar () {
// only if there is a currently selected range
if let selectedRange = textView.selectedTextRange {
// and only if the new position is valid
if let newPosition = textView.position(from: selectedRange.start, offset: -1) {
// set the new position
textView.selectedTextRange = textView.textRange(from: newPosition, to: newPosition)
}
}
}
。
func skipSpace () {
for _ in spaceCount...textView.text.count {
if checkSpace() == false {
nextChar()
}
}
}
我正在使用的扩展程序
extension String.UnicodeScalarView {
var length: Int {
return count
}
subscript (i: Int) -> String {
return self[i ..< i + 1]
}
func substring(fromIndex: Int) -> String {
return self[Swift.min(fromIndex, length) ..< length]
}
func substring(toIndex: Int) -> String {
return self[0 ..< Swift.max(0, toIndex)]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: Swift.max(0, Swift.min(length, r.lowerBound)),
upper: Swift.min(length, Swift.max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
}
然后,当单击按钮时,将调用这些功能和其他功能。
如果您知道如何提高速度,请提供帮助。
答案 0 :(得分:1)
我已修复它,现在它的速度要快得多。那是skipSpace()方法。
func skipSpace () {
for _ in spaceCount...textView.text.count {
if checkSpace() == false {
nextChar()
}
}
当我输入大量文本时,此循环范围会很大(spaceCount ... textView.text.count),因为它会获取textView中的字符数,因此只需将其更改为固定的数字即可,例如:( spaceCount ... 50),就是这样!
谢谢