在 super.init 初始化 self 之前在方法调用中使用 self



我看过许多类似的堆栈溢出问题,但没有太多帮助,因为它们与我需要的略有不同。

我正在创建一个UIView子类,如下所示。我想在初始化类时传递视图控制器并调用设置方法。

错误:

在 super.init 初始化 self 之前在方法调用 'setup' 中使用 self

法典:

class ProfilePhotoView: UIView{
var profileImage   =   UIImageView()
var editButton      =   UIButton()
var currentViewController   : UIViewController

init(frame: CGRect, viewController : UIViewController){
self.currentViewController = viewController
setup()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func setup(){
profileImage.image = UIImage(named: "profilePlaceHolder")
editButton.setTitle("edit", for: .normal)
editButton.setTitleColor(UIColor.blue, for: .normal)
editButton.addTarget(self, action: #selector(editPhoto), for: .touchUpInside)
profileImage.translatesAutoresizingMaskIntoConstraints  =   false
//addPhoto.translatesAutoresizingMaskIntoConstraints      =   false
editButton.translatesAutoresizingMaskIntoConstraints     =   false
self.addSubview(profileImage)
self.addSubview(editButton)
let viewsDict = [ "profileImage"    :   profileImage,
"editButton"       :   editButton
] as [String : Any]
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[profileImage]", options: [], metrics: nil, views: viewsDict))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[profileImage]", options: [], metrics: nil, views: viewsDict))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[editButton]", options: [], metrics: nil, views: viewsDict))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[profileImage]-10-[editButton]", options: [], metrics: nil, views: viewsDict))
}
func editPhoto(){
Utils.showSimpleAlertOnVC(targetVC: currentViewController, title: "Edit Button Clicked", message: "")
}

}

您没有从init(frame:viewController方法调用super.init(frame:)。它需要在设置self.currentViewController和调用setup之间完成。

init(frame: CGRect, viewController: UIViewController) {
self.currentViewController = viewController
super.init(frame: frame)
setup()
}

您应该阅读 Swift 一书的初始化章节(尤其是类继承和初始化部分(。类的初始化需要以明确记录的方式完成。

最新更新