我试图使用UILabel创建打字机动画效果,但无法找到任何答案。 UILabel是否是正确的使用对象?我希望文本在屏幕上打印一个字符串数组,例如,"登录...打开文件夹...重新启动系统.."我应该提一下,我是编码的新手,我已经尝试过搜索文档和API参考,但没有运气。我现在正在学习SWIFT,如果值得一提的话
答案 0 :(得分:8)
更新: Xcode 7.0 GM•Swift 2.0
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTypeWriter: UITextField!
let myText = Array("Hello World !!!".characters)
var myCounter = 0
var timer:NSTimer?
func fireTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "typeLetter", userInfo: nil, repeats: true)
}
func typeLetter(){
if myCounter < myText.count {
myTypeWriter.text = myTypeWriter.text! + String(myText[myCounter])
let randomInterval = Double((arc4random_uniform(8)+1))/20
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(randomInterval, target: self, selector: "typeLetter", userInfo: nil, repeats: false)
} else {
timer?.invalidate()
}
myCounter++
}
override func viewDidLoad() {
super.viewDidLoad()
fireTimer()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 1 :(得分:8)
我编写了一个名为CLTypingLabel的UILabel的子类,可以在GitHub上找到。这应该做你想要的。
安装CocoaPods后,将以下内容添加到您的Podfile中以使用它:
if created:
send_mail(...)
将标签的类别从UILabel更改为CLTypingLabel;
pod 'CLTypingLabel'
在运行时,设置标签文本将自动触发动画:
@IBOutlet weak var myTypeWriterLabel: CLTypingLabel!
您可以自定义每个字符之间的时间间隔:
myTypeWriterLabel.text = "This is a demo of typing label animation..."
您可以随时暂停输入动画:
myTypeWriterLabel.charInterval = 0.08 //optional, default is 0.1
此外,还有cocoapods
附带的示例项目答案 2 :(得分:7)
基于此答案: Letter by letter animation for UILabel?
我已将其更新为Swift 4,并使用DispatchWorkItem解决了CPU动画问题,以创建队列。
快捷键4
extension UILabel {
func setTextWithTypeAnimation(typedText: String, characterDelay: TimeInterval = 5.0) {
text = ""
var writingTask: DispatchWorkItem?
writingTask = DispatchWorkItem { [weak weakSelf = self] in
for character in typedText {
DispatchQueue.main.async {
weakSelf?.text!.append(character)
}
Thread.sleep(forTimeInterval: characterDelay/100)
}
}
if let task = writingTask {
let queue = DispatchQueue(label: "typespeed", qos: DispatchQoS.userInteractive)
queue.asyncAfter(deadline: .now() + 0.05, execute: task)
}
}
}
用法
label.setTextWithTypeAnimation(typedText: text, characterDelay: 10) //less delay is faster