Search code examples
swiftxcodemodel-view-controllerxcode-storyboard

In iOS, how to connect a Label to a View using a storyboard?


I'm making a simple iOS app and I've seen that you can connect a Label to a view controller using the storyboard by holding the control button and dragging from the Label to the view controller, creating an IBOutlet. I like how convenient this is.

I'm wondering how to make an IBOutlet to a view, not the view controller. I've made a custom view and put some Labels on it. I want these labels to be referenced in my view class, not the view controller. But XCode doesn't seem to let me make an IBOutlet unless I drag to a view controller. Is there a way around this?

The only other option I can think of is to create the Labels on the view programmatically, but I would rather not do this. I'm trying to keep the labels as part of the view, I don't think the view controller needs to know about them.

On the possible duplicate: My question is specific about trying to connect a Lable (or any control really) to a view rather than a view controller using the storyboard. The question linked is not specific, and seems more like a new user asking for help using xcode. The accepted answer there is not helpful to my question.


Solution

  • I feels like a workaround, but if you add the outlet to your custom view class first, then you can attach the outlet by dragging from the Referencing Outlet in XCode back to the View in Storyboard

    class CustomView: UIView
    {
        @IBOutlet weak var lblOne: UILabel!
    
        // do all the other stuff you need
    }
    

    enter image description here