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

≯℡__Kan透↙ 提交于 2019-12-31 05:27:10

问题


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.



来源:https://stackoverflow.com/questions/43926546/how-to-randomize-uilabel-text-each-time-the-view-controller-is-showed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!