How to randomize UILabel text each time the view c

2020-05-03 12:31发布

问题:

How do I make a label in my ViewController have a diffrent string of text each time the view crontroller is shown? Thanks! I'm using Swift 3

回答1:

Assuming you know how to add UILabel to your ViewController, here is quick sample how to pick random text on start:

class ViewController: UIViewController {
    let allTexts = ["Hey", "Hi", "Hello"]
    @IBOutlet weak var label: UILabel! //get UILabel from storyboard

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.label.text = self.allTexts[Int(arc4random_uniform(UInt32(self.allTexts.count)))]
    }
}

Adding this code to viewWillAppear will change your text anytime ViewController is about to appear - which means if you cover it with another ViewController (let's say popup) and then hide popup - it will change text.

If your prefer to just do it one time - when UIViewController is created put the same code inside viewDidLoad method.



标签: swift uilabel