2017-08-10 71 views
0

我看过很多类似的Stack Overflow问题没有太多帮助,因为它们与我需要的略有不同。在super.init初始化自我之前使用自我方法调用

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

错误:

Use of self in method call 'setup' before super.init initialises 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: "") 
    } 


} 

回答

3

你是不是从你的init(frame:viewController方法调用super.init(frame:)。它需要在设置self.currentViewController和致电setup之间完成。

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

    super.init(frame: frame) 

    setup() 
} 

你应该阅读本书雨燕的Initialization章(尤其是Class Inheritance and Initialization部分)。一个类的初始化需要以一个明确记录的方式完成。

相关问题