DixieFlatline
DixieFlatline

Reputation: 8035

What is the iPhone's equivalent of Android's findViewById(int)?

I come from Android and have just started learning iOS development. How can I reference UI elements created in the Interface Builder from code? In Android this can be done with the function findViewById().

What is the iOS SDK equivalent of findViewById()?

Upvotes: 9

Views: 3207

Answers (4)

yoAlex5
yoAlex5

Reputation: 34195

you have two variants:

  • set tag for view in .xib and find it via viewWithTag
  • use IBOutlet which connects view with class file

Upvotes: 1

Ahmad Kayyali
Ahmad Kayyali

Reputation: 8243

Set the control tag property and then retrieve the control by it's tag using viewWithTag.

tag: An integer that you can use to identify view objects in your application.

Example

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag = 1;
[myView addSubview:button]; 

Later on when you need to retrieve/access the UIButton control:

UIButton* btn = [myView viewWithTag:1];


Remember you can also Set the Tag property in your .xib (interface builder) file in the control attributes.

see Apple's UIView Class Reference Tag Property

Upvotes: 9

Ryan
Ryan

Reputation: 4668

Coming from the Jeff LeMarche school of beginning iPhone dev, you can also create member variables in your classes, decorate them as IBOutlet and link the UI elements in interface builder to the variables.

Here's a link to his beginning book on Google Books, page 52 goes into step by step details: http://books.google.com/books?id=TcP2bgESYfgC&lpg=PP1&dq=beginning%20iphone%203%20development&pg=PA52#v=onepage&q=connecting%20everything&f=false

Xcode 4 makes things, much easier to do the same. Simply open your .xib file, and in the "Editor" toolbar on the top right, click the middle button "Show the Assistant editor". This should open the related header (.h) file for that .xib, and you can simply control drag a UI element into the .h file and it'll generate the IBOutlet code for you.

Upvotes: 3

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

in iOS you could use viewWithTag function of UIView.

- (UIView *)viewWithTag:(NSInteger)tag

Use it as below

UIView* myView12 = [SuperViewOf_myView12 viewWithTag:12]

Upvotes: 1

Related Questions