Can I pass a function the name of a field to act on?

I am fairly new to Swift. I am writing an iPad app that has a number of UITextFields on the screen and I want to write one function that changes the properties of any of the text fields. I am hoping the function can get the name (or some other identifier) of the field to change from a parameter or pick it up from a variable. Is this possible? If so, what would be the syntax of the code to change a property, e.g. background colour, where the text field name is not 'hard coded' in the instruction?


In other words, a 'hard coded' instruction could be mytextfield.backgroundColor = UIColor.lightGrayColor(). I want to include this in a function where the field name in this instruction is variable.


Note that the text field will not necessarily be the 'first responder' when the function is called.


My apologies if this is a dumb question but I have spent hours reading docs and searching forums and cannot find an answer. Thanks.

So, you want to do this?

var fieldName = "backgroundColor"
mytextfield.setValue(value: UIColor.lightGrayColor(), forKey: fieldName)


I'm pretty sure you can do it like that, but only because UITextFields are Obj-C classes and inherit from NSObject. It's not a part of the Swift language. Also, it'll crash if mytextfield doesn't actually have a property with the passed-in name.

Incidentally, doing it by passing property names around is quite slow, if that matters for your app.

Hi Dave,


No. I want to do the following:


01. var fieldName = "sometextfield"

02. fieldName.backgroundColor = UIColor.lightGrayColor()


where the change in background color is performed on the field called 'sometextfield'


sorry if its not clear.

Assuming your class have:

    @IBOutlet var sometextfield: UITextField!

or:

    dynamic var sometextfield: UITextField!


You can write something like this:

        var fieldName = "sometextfield"
        self.setValue(UIColor.lightGrayColor(), forKeyPath: "\(fieldName).backgroundColor")


Search with "KVC Swift".

Thank you, this is just what I need. KVC is a new concept for me and will be very useful in my app.

Can I pass a function the name of a field to act on?
 
 
Q