Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference views programmatically without using IBOutlet

I am new to iOS programming and I am working with XCode learning storyboards. My question is

I have added the views that I want using the IB but I dont want to them to connect to my ViewController using Ctrl+Drag in the IB but do the same programmatically. I have seens posts suggesting to create instances of the views in code and add them (by setting frame) using addSubView(). But I dont want to hardcode my frame and sizes in code, I prefer IB for that. I only need to refer to them when I need.

In android, we can do the same by getIdByName() on the layout XML. I am looking for something similar.

Thanks

like image 873
2ndlife Avatar asked Jul 23 '26 08:07

2ndlife


1 Answers

In IB you can set the Tag property of the view and then reference it in code by using:

int buttonTagNumber = 2;
UIButton *myTaggedButton = (UIButton *)[self.view viewWithTag:buttonTagNumber];

Tags are just an int, you can have as many of them as you like. Note that if you have the same tag on 2 different views within one heirarchy, the behaviour is undefined and it will grab the first one of these it finds.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!