2

I have several textfields (and labels) in my XIB and at some point in my application I build dynamicaly a string which contains a control name (i.e. one of the textfields). How can I refer to the actual textfield using the string I created that holds the name of the textfield.

For example, I have txt1 , txt2, txt3, txt4 as UITextFields and i have a string (str) that contains one of the fields above names (str ="txt3") then i want to change the content of the uitextfield txt3 since str have "txt3" at this point.

How do I cast from the string to the actual control?

Brandon Schlenker
  • 5,078
  • 1
  • 36
  • 58
Stk Stocki
  • 139
  • 3
  • 8

1 Answers1

3

If the UITextFields all have a backing property then you can use KVC to get a reference to the control and then you just use it as normal.

NSString *str = @"txt1";
UITextField *myTextField = [self valueForKey:str];
myTextField.text = @"what ever you want to update to";

Side note

Although you have not mentioned the source of str @JefferyThomas raises a very valid point about not trusting use input that has not been validated.

Paul.s
  • 38,494
  • 5
  • 70
  • 88
  • I think it's important to note may not be such a good idea. At least, you will want to rigorously scrub any user input before you start executing code like this. – Jeffery Thomas May 16 '12 at 21:14
  • I should have clarified, no user involvment here, the application build the str field according to some logic. no user input for that field. Thanks for your comment it worked as i wanted.! – Stk Stocki May 16 '12 at 21:32
  • If this solved your problem then just hit the accept answer button, so people know what the solution is. – Paul.s May 16 '12 at 21:45
  • Hi Paul, I don't see any 'accept answer' button only 'was it useful to you' which I clicked Yes. what am i missing? – Stk Stocki May 17 '12 at 02:15
  • @StkStocki - this confused me, too when I started using SO. To accept an answer, click the checkbox that appears underneath the large number (of up votes) at the upper left of the answer. – danh May 17 '12 at 03:03