Ahmed Bahgat
Ahmed Bahgat

Reputation: 141

Why I can not addSubview to my view when I work programmatically?

I am trying to add a subview to a containerView and this subview is basically a textfield view but I get this compile time error "Instance member 'commentTextField' cannot be used on type 'CommentsController'" and I solved the problem by placing lazy var instead of let, but I can not get the point behind declaring the containerView as lazy var instead of let

mycode

let commentTextField :UITextField = {
         let tf = UITextField()
          tf.placeholder = "Enter comment"
          return tf
      }()

let containerView:UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .white
        containerView.frame = CGRect(x: 0, y: 0, width:100, height: 50)
        containerView.addSubview(commentTextField)
        commentTextField.setAnchor(top: containerView.topAnchor, left: containerView.leftAnchor, right: submitButton.leftAnchor, bottom: containerView.bottomAnchor, paddingBottom: 0, paddingLeft: 5, paddingRight: 0, paddingTop: 0, height: 0, width: 0)
        return containerView
}

Upvotes: 0

Views: 613

Answers (1)

messeb
messeb

Reputation: 377

That's because the closure of the property is called during initialisation of the type. In your case that is a subclass of UIViewController, if your properties are in a custom view controller.

And during the initialisation of a type you can't access self (UIViewController in your case) and properties or methods of self.

Via lazy you can solve this.

Upvotes: 1

Related Questions