上一次在显示文本的一个字符 swift 2.0

发布时间: 2016/5/7 18:55:38
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

新的 Swift 2.0; 试着去学习它,对感兴趣的动画和试着编写一些代码来一次在屏幕一个字符上显示一条消息。

我写这个,它工作,但我不能帮助我不能与 CALayers 的东西也许和/或 alpha 值吗?或一些动画的发明,更多的东西 swift 值得; 这感觉和看起来有点笨拙,排序 1977年真的。

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


let supertext  = "A long time ago, in a galaxy far, far away ..."
let round = supertext.characters.count
for i in 0...round {
    let delay = Double(i)/10
    let subtext = supertext[supertext.startIndex..<supertext.startIndex.advancedBy(i)]
    NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "ghostText:", userInfo: ["theText" :subtext], repeats: false)
    }
}

var view3:UITextView = UITextView()

func ghostText(timer:NSTimer) {
    view3.removeFromSuperview()
    let userInfo = timer.userInfo as! Dictionary<String, AnyObject>
    let tempText:NSString = (userInfo["theText"] as! NSString)
    print(tempText)

    let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0)
    let textFont = [NSFontAttributeName:font]

    let subChararacter = NSAttributedString(string: String(tempText), attributes: textFont)
    view3.frame = CGRect(x: 100, y: 120, width: CGRectGetWidth(self.view.frame), height: CGRectGetWidth(self.view.frame)-20)
    view3.attributedText = subChararacter
    self.view.addSubview(view3)
}

解决方法 1:

我想 Swiftworthy 是主观的但这里是另一个实现基于代码如何目前工作包装在 NSTimer Swift 类。

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
        }
    }
}
官方微信
官方QQ群
31647020