我正在制作一款ios-app,这是一本诗集。我想要的功能之一是定时“阅读”,所以诗中的文字与我阅读时的时间相同。所以我有一个数组,里面有诗中的文字,与延迟配对。
现在我想循环翻译单词,在screeen上绘制数字1,等待相应的时间段,绘制单词2,等待等等...我的问题是,如果某人有一个优雅的方式og实现这一点 - 或者只是一种运作方式;-)这比我想象的要困难......
我使用Swift 4.到目前为止,我已经在Imageview中绘制了单词,但之后我只得到了最终生成的图像,而且我也宁愿不用延迟锁定mainthread。所以我认为解决方案是以某种方式使用调度,但我不在我的深度。任何人? 对于可以演示在视图中绘制文本的单词的代码非常有帮助,所以出现的单词时间指定为数字列表(毫秒或其他)。
答案 0 :(得分:1)
嗯,我认为没有真正“干净”的做法。以下是我将如何尝试:
func showWords(words: [String]) {
var a: DispatchTime = DispatchTime(uptimeNanoseconds: 0) // the delay in nanoseconds (most precise way)
for each in words {
let animationTime = 0.3 // you'll need to find a way to calculate how long it takes for each word to appear
a = DispatchTime(uptimeNanoseconds: a + (animationTime*1000000000)) // calculate ddispatch time in nanoseconds
DispatchQueue.main.asyncAfter(deadline: .now() + a, execute: {
self.writeWord(each)
})
}
}
这基本上做的是它一次动画所有单词,但它会使每个单词的动画具有它需要完成计算之前的延迟。这就是我打字机的效果。但是,我不得不体验较旧的iPhone往往有点不知所措,因为这种方法非常阻塞主线程。
答案 1 :(得分:1)
这是一种方法,它使用反射方法并动画显示单词以及将延迟设置为下一个单词。 display(poem:)
函数可以完成所有工作,但是您可以在这里完成整个测试项目,只需在故事板中创建UITextField
和UIButton
并链接它们:
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
let poem = [("Test ", 0.6), ("my ", 0.4), ("core ", 1.0), ("just ", 0.6), ("like ", 0.4), ("be", 0.4), ("fore", 0.6)]
@IBAction func animate(_ sender: Any) {
display(poem: poem)
}
func display(poem: [(word: String, delay: TimeInterval)]) {
guard let first = poem.first else { return }
UIView.transition(with: textView,
duration: first.delay,
options: .transitionCrossDissolve,
animations: { self.textView.text.append(first.word) },
completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + first.delay) {
self.display(poem: Array(poem.dropFirst()))
}
}
}