这是一个打字动画,它以固定的时间间隔将数组中的字符添加到文本字段的文本中:
@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的字符(就像它是一个打字动画,但删除字符)。但是,我无法弄明白。
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++
}
我想用空字符串替换每个字符,但它不起作用(字符串的随机字母被替换)。我该如何修复我的代码?
答案 0 :(得分:4)
为什么不这样做:
func deleteLetter() {
if textFieldMain.text != "" {
textFieldMain.text = str.substringToIndex(textFieldMain.text.endIndex.predecessor())
} else {
typingAnimationTimer?.invalidate()
}
}
顺便说一句,如果你用&#34重复启动计时器:重复:#34;在fireDeletionTimer()
您不需要在deleteLetter()
此外,stringByReplacingOccurrencesOfString()
会清除文本中该字母的每个实例,而不仅仅是最后一个。
答案 1 :(得分:1)
我会将deleteLetter()
方法重写为以下内容:
func deleteLetter() {
myString = myString.substringToIndex(myString.endIndex.predecessor())
textFieldMain.text = myString
typingAnimationTimer?.invalidate()
if myString.characters.count > 0 {
typingAnimationTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "deleteLetter", userInfo: nil, repeats: false)
}
}
编辑:看起来Zoltan已经打败了我。