我在没有太多帮助的情况下查看了许多类似的Stack Overflow问题,因为它们与我的需求略有不同。
我正在创建UIView
的子类,如下所示。我想在初始化类时传递一个视图控制器并调用setup方法。
错误:
在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: "")
}
}
答案 0 :(得分:3)
您没有使用super.init(frame:)
方法致电init(frame:viewController
。需要在设置self.currentViewController
和调用setup
之间完成。
init(frame: CGRect, viewController: UIViewController) {
self.currentViewController = viewController
super.init(frame: frame)
setup()
}
您应该阅读Swift书的Initialization章节(尤其是Class Inheritance and Initialization部分)。课程的初始化需要以清晰的文件形式完成。