键入动画:删除字符 [英] Typing animation: deleting characters
问题描述
这是一个打字动画,它以固定的时间间隔将数组中的字符添加到文本字段的文本中:
Here's a typing animation that adds up characters from an Array to the text of a text field at a fixed time interval:
@IBOutlet weak var textFieldMain: UITextField!
var myText = Array("Hi! I'm Cesare.".characters)
var myString = "Hi! I'm Cesare."
var typingAnimationCounter = 0
var typingAnimationTimer: NSTimer?
func fireTimer() {
typingAnimationTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "typeLetter", userInfo: nil, repeats: true)
}
func typeLetter() {
if typingAnimationCounter < myText.count {
textFieldMain.text = textFieldMain.text! + String(myText[typingAnimationCounter])
typingAnimationTimer?.invalidate()
typingAnimationTimer = NSTimer.scheduledTimerWithTimeInterval(0.15, target: self, selector: "typeLetter", userInfo: nil, repeats: false)
} else {
typingAnimationTimer?.invalidate()
}
typingAnimationCounter++
}
我想现在删除textField的字符(就好像它是一个打字动画,但删除字符)。我不明白怎么做。
I would like to have characters of the textField deleted now (like if it was a typing animation, but by deleting characters). I can't figure out how, though.
func fireDeletionTimer() {
typingAnimationTimer = NSTimer.scheduledTimerWithTimeInterval(0.45, target: self, selector: "deleteLetter", userInfo: nil, repeats: true)
}
func deleteLetter() {
if typingAnimationCounter < myText.count - 1 {
let index = myString.characters.count - typingAnimationCounter - 1
textFieldMain.text = myString.stringByReplacingOccurrencesOfString(String(myText[index]), withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
typingAnimationTimer?.invalidate()
typingAnimationTimer = NSTimer.scheduledTimerWithTimeInterval(0.45, target: self, selector: "deleteLetter", userInfo: nil, repeats: false)
} else {
typingAnimationTimer?.invalidate()
}
typingAnimationCounter++
}
我想用空字符串替换每个字符,但它不起作用(字符串的随机字母被替换)。如何修复我的代码?
I thought of replacing every single character with an empty String, but it doesn't work (random letters of the string are replaced). How can I fix my code?
推荐答案
为什么不执行以下操作:
Why not do the following:
func deleteLetter() {
if textFieldMain.text != "" {
textFieldMain.text = str.substringToIndex(textFieldMain.text.endIndex.predecessor())
} else {
typingAnimationTimer?.invalidate()
}
}
顺便说一句,如果你在 fireDeletionTimer()
中用重复:真启动你的计时器,你不需要再次重新创建它再次在 deleteLetter()
By the way, if you start your timer with "repeats: true" in fireDeletionTimer()
you don't need to recreate it again and again in deleteLetter()
此外, stringByReplacingOccurrencesOfString()
清除文本中该字母的每个实例,而不仅仅是最后一个。
Also, stringByReplacingOccurrencesOfString()
clears every instance of that letter in your text, not just the last one.
这篇关于键入动画:删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!