2017-08-10 69 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部分)。一個類的初始化需要以一個明確記錄的方式完成。

相關問題