Matt Falkner
Matt Falkner

Reputation: 65

How to print a string one letter at a time into a textview SWIFT

How do I print my variable eg. var Output:String = "Test" so that It prints into the textview one letter at a time? Like it's being typed out. Thanks in advance!

Upvotes: 1

Views: 825

Answers (3)

Fogmeister
Fogmeister

Reputation: 77641

I wrote a blog post recently where I created a similar but different effect. In my example I did it using a UILabel and NSAttributedStrings.

In mine I used a fade in animation but you needn't do that if you don't want.

Given that you just want it letter by letter it will make it a lot less complex than mine.

Anyway, it should give you an idea of how I would approach it. Also, unless the use is actually typing into the UITextView then don't use one. Use a UILabel instead.

http://www.oliverfoggin.com/birdman-and-text-animations/

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236370

You can use a timer with a random interval as follow:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myTypeWriter: UITextField!
    let myText = Array("Hello World !!!")
    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.
    }
}

Upvotes: 1

Arbitur
Arbitur

Reputation: 39081

This should loop trough every character inside the provided string and print it out with delay

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
    for char in "test" {
        dispatch_async(dispatch_get_main_queue()) { textView.text += String(char) }
        usleep(1000)
    }
}

Upvotes: 0

Related Questions