Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an @IBOutlet in a custom view?

I've created a view on the storyboard in one of my view controllers and realized that I'll need to reuse it. So I then created a subclass for UIView to consolidate the code. I've selected the view in the storyboard and changed the class to my custom view class. Now I want to create @IBOutlets for a couple of the components in the view (in this case, 2 text fields). When I try and drag&drop from storyboard to custom view file, the only thing it allows me to create is an @IBAction and @IBOutlet is grayed out.

I tried creating the @IBOutlet manually in code and then drag from the circle to the component on the storyboard. Everything seemed to work (i.e. I see the connection in the little black popup and also the circle next to the variable is filled in. But when I run the app, the 2 fields are nil.

Is there a reason why I can only create actions and not outlets? (I'm kind of new to iOS dev).

like image 566
u84six Avatar asked Dec 12 '17 00:12

u84six


2 Answers

No XIB is needed

  1. Manually write the IBOutlet in your custom UIView class, for example: @IBOutlet weak var container: UIView!

  2. Open the storyboard and select the custom view in the Document Outline panel on the left.

  3. Open the Connections Inspector on the right. Drag from the Outlet to the custom view in the Document Outline panel to connect them.

Connect custom view's IBOutlet to view in Interface Builder

like image 161
invisible squirrel Avatar answered Sep 28 '22 06:09

invisible squirrel


If you want to reuse a UIView then best to create an xib of the view and a custom class of the UIView. Then change the file owner in xib class to your custom class. Then you can drag and drop IBOutlets of the components inside the view to custom class. In the storyboard you can use the custom view and change the name of the class of view to custom view. Now drag and drop the IBOutlets from the story board to UIView. You can see the tutorial video on how to do , I have made for you. https://youtu.be/IrgH522lbfA

like image 31
Rahul Dasgupta Avatar answered Sep 28 '22 08:09

Rahul Dasgupta