Chameleon
Chameleon

Reputation: 1608

Set CustomView delegate before init

Although I could create a func setImages () in my CustomView class and call this after initializing myCustomView, I would like to understand if there's a cleaner way to set a view's delegate so that it is accessible when being initialized.

My main ViewController contains

class Main: UIViewController, CustomViewDelegate {

    var imagesArray:[UIImage] = [Image1,Image2,Image3,Image4,Image5]

    var myCustomView = CustomView()

    override func viewDidLoad() {
        super.viewDidLoad()

        myCustomView.delegate = self
        myCustomView = CustomView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        //this causes init of CustomView, but delegate is now nil and button images don't load
    }
}

My CustomView file contains

var buttonsArray = [Button1,Button2,Button3,Button4,Button5]

override init(frame: CGRect) {
    super.init(frame : frame)       

    for n in 0..< buttonsArray.count {
        buttonsArray[n].setImage(delegate?.imagesArray[n], for: .normal)
    }
}

Upvotes: 0

Views: 474

Answers (1)

Agent Smith
Agent Smith

Reputation: 2923

You can create a new initializer which takes a frame and a delegate type and set the delegate before you set images to buttons

 init(frame: CGRect,sender: CustomViewDelegate) {
    super.init(frame : frame)

    self.delegate = sender

    for n in 0..< buttonsArray.count {
       buttonsArray[n].setImage(delegate?.imagesArray[n], for: .normal)
    }
}

For that, you have to confirm your viewController for the delegate(obviously).Call your customView like this in viewController:

class ViewController: UIViewController, CustomViewDelegate {

    var myCustomView: CustomView!        

    override func viewDidLoad() {

       myCustomView = CustomView(frame: self.view.bounds, sender: self)
    }
}

hope it helps!

Upvotes: 3

Related Questions