Nicholas Muir Nicholas Muir - 1 year ago 105
Swift Question

IBOutlet for element in containerview inside original viewcontroller

In my main view I have two containers that have an IBOutlet in view controller.

In both the containers I have a an image and a label as in the picture below.

enter image description here

I want to have an IBOutlet to change the image and label but when I drag it to the original view controller it doesn't allow it.

So in the viewcontroller.swift as I said I can access each container by clicking and dragging. Like this

@IBOutlet weak var containerview1: UIView!
@IBOutlet weak var containerview2: UIView!

But I am trying to access the image view and labels in the container, something like this:

@IBOutlet weak var containerview1: UIView!
@IBOutlet weak var containerview2: UIView!

@IBOutlet weak containerview1_ImageView: UIImageView!
@IBOutlet weak containerview2_ImageView!: UIImageView!

I understand that this is probably not the correct way to do it. I need to be able to change the image and label in both of the containerviews programatically through viewcontroller.swift.

Thanks for your help

Answer Source

Create two seperate class for containers

import UIKit

class ContainerView1: UIView {

@IBOutlet var containerView1Label: UILabel!
@IBOutlet var containerView1ImageView: UIImageView!


import UIKit

class ContainerView2: UIView {

@IBOutlet var containerView2Label: UILabel!
@IBOutlet var containerView2ImageView: UIImageView!


In main viewController storyboard define those class

enter image description here

Now set the label and imageview outlet by dragging from storyboard

enter image description here

Now drag container outlets in main view controller and use

import UIKit

class ViewController: UIViewController {

    @IBOutlet var containerView1: ContainerView1!
    @IBOutlet var containerView2: ContainerView2!

    override func viewDidLoad() {
    // Do any additional setup after loading the view, typically from a nib.

    // use like this both container elements

    containerView1.containerView1Label.text = "Container view 1 lable"
    //containerView1.containerView1ImageView.image = yourImage file

    override func didReceiveMemoryWarning() {
    // Dispose of any resources that can be recreated.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download