在init之前设置CustomView委托

时间:2018-02-28 06:32:55

标签: swift delegates custom-view

虽然我可以在我的CustomView类中创建func setImages ()并在初始化myCustomView后调用它,但我想了解是否有更简洁的方法来设置视图的委托以便在访问时可以访问它初始化。

我的主ViewController包含

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
    }
}

我的CustomView文件包含

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)
    }
}

1 个答案:

答案 0 :(得分:3)

您可以创建一个新的初始化程序,它采用框架委托类型,并在将图像设置为按钮之前设置委托

 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)
    }
}

为此,你必须为委托确认你的viewController(显然)。在viewController中调用你的customView:

class ViewController: UIViewController, CustomViewDelegate {

    var myCustomView: CustomView!        

    override func viewDidLoad() {

       myCustomView = CustomView(frame: self.view.bounds, sender: self)
    }
}
希望它有所帮助!