swiftuikitnslayoutconstraint

Can't activate NSLayoutConstraint


I'm trying to set up UI for ViewController through NSLayoutConstraint. Here's the code I'm using:

class ProfileViewController: UIViewController {

    private var profileUser = katyPerry
    
    private var profileImage: UIImageView {
        let imageView = UIImageView(image: UIImage(named: profileUser.login))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }

    override func viewDidLoad() {
        //profileUser = users.randomElement() ?? User(login: "default", name: "default")
        super.viewDidLoad()
        setUpView()
    }
    
    func setUpView() {
        view.addSubview(profileImage)
        NSLayoutConstraint.activate([
            profileImage.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            profileImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
            profileImage.heightAnchor.constraint(equalToConstant: 100),
            profileImage.widthAnchor.constraint(equalToConstant: 100)
        ])
    }
}

When running the app, it throws an Error when accessing the view. Xcode highlight .activate and gives following description: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10).

How to fix this?


Solution

  • The problem is that every time you say profileImage you are creating a new image view. So you are talking about five different image views in just one little piece of code:

    view.addSubview(profileImage) // image view 1
    NSLayoutConstraint.activate([
        profileImage.leadingAnchor..., // image view 2
        profileImage.topAnchor..., // image view 3
    // ... and so on
    

    To fix the problem, change

    private var profileImage: UIImageView {
        let imageView = UIImageView(image: UIImage(named: profileUser.login))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }
    

    To

    private lazy var profileImage: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: profileUser.login))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()