我正在尝试以textView
,一次显示字母,并且延迟,但我无法正确显示。
我希望它看起来像是在打字。这是我目前的代码:
let delay = 2.0 * Double(NSEC_PER_SEC)
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
let localmessage = message + "\n"
for letter in localmessage.characters {
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.textView.text = self.textView.text + String(letter)
})
}
答案 0 :(得分:4)
您正在使用相同的dispatchTime,因此所有字符都将同时显示。您需要在for循环中增加dispatchTime以一次显示一个字符。
试试这样:
let localmessage = message + "\n"
var myInt = 1
for letter in localmessage.characters {
let delay = 2.0 * Double(NSEC_PER_SEC) * Double(myInt)
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.textView.text = self.textView.text + String(letter)
})
myInt = myInt + 1
}
答案 1 :(得分:2)
这是我怎么做的
let message = "hello world"
var index:Double = 1.0
let delayInSeconds = 0.5
for letter in message.characters {
runAfterDelay(delayInSeconds * index, block: {
self.firstTextField.text = self.firstTextField.text! + String(letter)
})
index = index + 1
}
}
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
runAfterDelay函数在很多情况下证明非常方便所以我喜欢保留它:)
答案 2 :(得分:0)
您可以尝试使用NSTimer,而不是GCD:
var index = 0
var timer = NSTimer()
override func viewDidLoad() {
super.viewDidLoad()
timer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(ViewController.updateTextView), userInfo: nil, repeats: true)
}
func updateTextView() {
let letter = localmessage.characters[index]
self.textView.text = self.textView.text + String(letter)
index++
if index == localmessage.characters.count {
timer.invalidate()
}
}
答案 3 :(得分:0)
为什么不简单地使用计时器?
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
let message = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
override func viewDidLoad() {
super.viewDidLoad()
self.typingTimer()
}
func typingTimer() {
var localMessage = message
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { timer in
if localMessage.characters.count > 0 {
self.textView.text.append(localMessage.characters.remove(at: localMessage.characters.startIndex))
} else {
timer.invalidate()
}
})
}
}