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()
?
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];
Tag
property in your .xib (interface builder) file in the control attributes.
see Apple's UIView Class Reference Tag Property
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.
in iOS you could use viewWithTag
function of UIView
.
- (UIView *)viewWithTag:(NSInteger)tag
Use it as below
UIView* myView12 = [SuperViewOf_myView12 viewWithTag:12]
you have two variants:
viewWithTag
IBOutlet
which connects view with class fileIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With