Displaying text one character at a time in swift 2.0

扶醉桌前 提交于 2019-11-28 11:42:58

I suppose Swiftworthy is subjective, but here's another implementation based on how your code currently works that wraps the NSTimer in a Swift class.

class Timer {
    typealias TimerFunction = (Int)->Bool
    private var handler: TimerFunction
    private var i = 0

    init(interval: NSTimeInterval, handler: TimerFunction) {
        self.handler = handler
        NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "timerFired:", userInfo: nil, repeats: true)
    }

    @objc
    private func timerFired(timer:NSTimer) {
        if !handler(i++) {
            timer.invalidate()
        }
    }
}

class ViewController: UIViewController {
    let text: NSAttributedString = {
        let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
        return NSAttributedString(string: "A long time ago, in a galaxy far, far away ...", attributes: [NSFontAttributeName: font])
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        let textView = UITextView(frame: CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20))
        self.view.addSubview(textView)

        let _ = Timer(interval: 0.1) {i -> Bool in
            textView.attributedText = self.text.attributedSubstringFromRange(NSRange(location: 0, length: i+1))
            return i + 1 < self.text.string.characters.count
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!