Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Created December 9, 2015 15:36
Show Gist options
  • Save samuelbeek/4b2f04e2dbd44a5093a2 to your computer and use it in GitHub Desktop.
Save samuelbeek/4b2f04e2dbd44a5093a2 to your computer and use it in GitHub Desktop.
Typewriting effect in swift
//
// TypingLabel.swift
//
// Created by Samuel Beek on 09/12/15.
// Copyright © 2015 Samuel Beek. All rights reserved.
//
import UIKit
import SwiftyTimer
class TypingLabel : UILabel {
var timer : NSTimer?
var interval = 0.05
var waitInterval = 1.3
func sequence(strings: [String]) {
for (index, string) in strings.enumerate() {
NSTimer.after(waitForIndex(index, strings: strings), {
self.addAndRemoveText(string)
})
}
}
func loop(strings: [String]) {
sequence(strings)
let wait = waitForIndex(strings.count, strings: strings)
NSTimer.after(wait, {
self.loop(strings)
})
}
func waitForIndex(index: Int, strings: [String]) -> NSTimeInterval {
var wait = 0.0
for (i, string) in strings.enumerate() {
if i < index {
wait = wait + timeFor(text: string) * 2
}
}
return wait
}
func addAndRemoveText(string: String) {
addText(string)
NSTimer.after(timeFor(text: string), {
self.emptyText()
})
}
func timeFor(text text: String) -> NSTimeInterval {
return (Double(text.characters.count)*interval) + interval + waitInterval
}
func emptyText() {
timer = NSTimer.after(interval, {
self.removeLetter()
})
}
func removeLetter() {
if let text = self.text where text.characters.count > 0 {
self.text = String(text.characters.dropLast())
timer?.invalidate()
timer = NSTimer.after(interval, {
self.removeLetter()
})
}
}
func addText(text: String) {
if text.characters.count > 0 {
timer = NSTimer.after(interval, {
self.addLetter(text[text.startIndex])
self.timer?.invalidate()
self.addText(String(text.characters.dropFirst()))
})
}
}
func addLetter(letter: Character) {
self.text?.append(letter)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment