尽管我可以在CustomView类中创建一个func setImages (),并在初始化myCustomView后调用它,但我想知道是否有更干净的方法来设置视图的委托,以便在初始化时可以访问它。
我的主视图控制器包含

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

最佳答案

您可以创建一个新的初始值设定项,它接受一个框架和一个委托类型,并在将图像设置为按钮之前设置委托

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

希望有帮助!

关于swift - 在初始化之前设置CustomView委托(delegate),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49023310/

10-12 01:32