Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 693
DixieFlatline Avatar asked Apr 27 '11 15:04

DixieFlatline


4 Answers

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

like image 160
Ahmad Kayyali Avatar answered Nov 02 '22 14:11

Ahmad Kayyali


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.

like image 27
Ryan Avatar answered Nov 02 '22 14:11

Ryan


in iOS you could use viewWithTag function of UIView.

- (UIView *)viewWithTag:(NSInteger)tag

Use it as below

UIView* myView12 = [SuperViewOf_myView12 viewWithTag:12]
like image 1
Jhaliya - Praveen Sharma Avatar answered Nov 02 '22 13:11

Jhaliya - Praveen Sharma


you have two variants:

  • set tag for view in .xib and find it via viewWithTag
  • use IBOutlet which connects view with class file
like image 1
yoAlex5 Avatar answered Nov 02 '22 14:11

yoAlex5