Search code examples
iosswift2ibactioniboutlet

create IBOutlet / IBAction & connect it with UI in a custom class


In my ViewController, I have two UIImageView which have IBOutlet connection to UI :

class ViewController: UIViewController {
    @IBOutlet weak var img1: UIImageView!
    @IBOutlet weak var img2: UIImageView!
    ...

Now, I want to refactor my project to have a dedicated class ImageManager handles the images. So, the ViewController becomes like this :

class ViewController: UIViewController {
   var imgMgr: ImageManager!

   override func viewDidLoad() {
        super.viewDidLoad()
        imgMgr = ImageManager()
   }
}

I want the ImageManager class to declare the two UIMageViews the same way as that in ViewController and make the IBOutlet connection with UI, but looks like it doesn't work in this way:

class ImageManager : NSObject {
    @IBOutlet weak var img1: UIImageView!
    @IBOutlet weak var img2: UIImageView!
    ...
}

Is there any way to make a custom class holding the IBOutlet & IBAction which connects to interface builder UI components (instead of doing it in ViewController)?


Solution

  • I don't think you should do this. You should just manage your images in your custom UIImage class using for example:

    //inside the function awakFromNib
        self.layer.cornerRadius = 5.0 //will make all the images' corner radius of elements assigned to this custom class rounded
        self.clipsToBounds = true
    

    Then you will drag the image outlets as usual to the view controller, but instead of setting its class to "UIImage", set it to the custom class name

    @IBOutlet weak var someImg: CustomImgClass!