Reputation: 23
I have the following code in my viewcontroller:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Button: UIButton!
@IBOutlet weak var Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let names = ["Name1", "Name2", "Name3", "Name4"]
let randomName = names.randomElement()!
self.Label.text=randomName;
}
}
How can I make the button "button", when pressed, make the label a different random item from the array "names"?
Upvotes: 0
Views: 352
Reputation: 347314
Make names
an instance level property (rather then been declared locally to viewDidLoad
)
Create a "interface builder action function", wire this to your button in the story board.
In this action function, simply pick a random word and assign it to the label.
For example...
let names = ["Name1", "Name2", "Name3", "Name4"]
//...
@IBAction
func pickRandomWord(_ sender: Any) {
let randomName = names.randomElement()!
self.Label.text=randomName;
}
Upvotes: 1
Reputation: 686
If you want to do it programmatically, you can check addTarget() https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget
Upvotes: 0