简体   繁体   中英

How can I use the value of a swift string as the name of an UIObject to edit?

Is it possible to edit an UIObject with the value of a swift string? If I for example have to change the backgroundcolor of a button created in the storyboard of a swift iOS project, and I cannot write the name, but that the name is the value of a string. Is it then possible to change the backgroundcolor of the button? The reason I'm trying to do this, is that I have a lot of buttons that calls a function with the parameter of their own name when pressed. When it's done the function knows which button to color red. I have tried something like this:

@IBOutlet weak var PressMeButtonOutlet: UIButton!
@IBAction func PressMeButtonAction(sender: AnyObject) {
    reColor("PressMeButtonOutlet")
}    


func reColor (buttonName: String) {

\(buttonName).backgroundColor = UIColor.redColor()

When a UIButton triggers an IBAction , it sends its own reference as the sender.

So the easy way to do it is this:

@IBAction func PressMeButtonAction(sender: UIButton) {
    reColor(sender)
}    


func reColor (button: UIButton) {

    button.backgroundColor = UIColor.redColor()
}

Notice that I have changed the IBAction parameter to UIButton .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM