我有一个具有固定宽度和高度的
uitextview
。
为了使文本更容易理解,我想执行逐个字符的输入“动画”,并且能够使用
Timer
对象使其工作。
我唯一的问题是......当输入的第一个字符会溢出到下一行时,它不会在下一行输入第一个字符,而是在当前行输入。当输入到达
uitextview
末尾时,该单词之前输入的所有字符才会被带到下一行。
这会导致打字动画不稳定,我想知道是否可以通过提前在新行上输入第一个字符来使其变得更流畅。任何指导将不胜感激!
这是我当前的功能:
func type(text: String) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.paragraphSpacing = 10
let bodyAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.black,
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)
]
let characters = Array(text)
var characterIndex = 0
let attributedString = NSMutableAttributedString()
Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] timer in
guard let self = self else { return }
while characters[characterIndex] == " " {
attributedString.append(NSAttributedString(string: " ", attributes: bodyAttributes))
textView.attributedText = attributedString
characterIndex += 1
if characterIndex == characters.count {
timer.invalidate()
return
}
}
let char = String(characters[characterIndex])
attributedString.append(NSAttributedString(string: char, attributes: bodyAttributes))
textView.attributedText = attributedString
characterIndex += 1
if characterIndex == characters.count {
timer.invalidate()
}
}
}
func type(text: String, into textView: UITextView) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.paragraphSpacing = 10
let bodyAttributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.black,
.paragraphStyle: paragraphStyle,
.font: UIFont.systemFont(ofSize: 17)
]
var characterIndex = 0
var currentLine = 0
var currentLineLength = 0
let words = text.components(separatedBy: .whitespaces)
Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { timer in
guard characterIndex < text.count else {
timer.invalidate()
return
}
let char = String(text[text.index(text.startIndex, offsetBy: characterIndex)])
let attributedString = NSMutableAttributedString(attributedString: textView.attributedText ?? NSAttributedString())
if char == " " {
attributedString.append(NSAttributedString(string: " ", attributes: bodyAttributes))
textView.attributedText = attributedString
characterIndex += 1
currentLineLength += 1
} else {
if currentLineLength >= textView.frame.width / textView.font!.pointSize {
currentLine += 1
attributedString.append(NSAttributedString(string: "\n", attributes: bodyAttributes))
textView.attributedText = attributedString
currentLineLength = 0
}
attributedString.append(NSAttributedString(string: char, attributes: bodyAttributes))
textView.attributedText = attributedString
characterIndex += 1
currentLineLength += 1
}
}
}
在这