How to randomize UILabel text each time the view controller is showed

前端 未结 1 925
深忆病人
深忆病人 2021-01-27 11:34

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条回答
  • 2021-01-27 11:55

    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.

    0 讨论(0)
提交回复
热议问题