1

I've looked at many similar Stack Overflow questions without much help as they were slightly different to what I need.

I am creating a subclass of UIView as show below. I would like to pass a view controller and call setup method when I initialise the class.

Error:

Use of self in method call 'setup' before super.init initialises self

Code:

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


}
Rajamohan S
  • 7,229
  • 5
  • 36
  • 54
SpaceX
  • 2,814
  • 2
  • 42
  • 68

1 Answers1

4

You are not calling super.init(frame:) from your init(frame:viewController method. It needs to be done between setting self.currentViewController and calling setup.

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

    super.init(frame: frame)

    setup()
}

You should read the Initialization chapter (especially the Class Inheritance and Initialization section) of the Swift book. Initialization of a class needs to be done in a clearly documented fashion.

rmaddy
  • 314,917
  • 42
  • 532
  • 579