每次显示视图控制器时如何随机化 UILabel 文本 [英] How to randomize UILabel text each time the view controller is showed
问题描述
每次显示视图控制器时,如何使我的 ViewController 中的标签具有不同的文本字符串?谢谢!我正在使用 Swift 3
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
推荐答案
假设您知道如何将 UILabel
添加到您的 ViewController
,这里是如何选择随机的快速示例开始时的文字:
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)))]
}
}
将此代码添加到 viewWillAppear
将在 ViewController 即将出现时更改您的文本 - 这意味着如果您用另一个 ViewController 覆盖它(假设弹出窗口)然后隐藏弹出窗口 - 它会更改文本.
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.
如果您更喜欢只做一次 - 在创建 UIViewController 时将相同的代码放入 viewDidLoad
方法中.
If your prefer to just do it one time - when UIViewController is created put the same code inside viewDidLoad
method.
这篇关于每次显示视图控制器时如何随机化 UILabel 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!