Search code examples
iosswiftuiimageviewconstraints

Set UIImageView Constraints programatically and activate the same


I have existing view in which I need to add UIImageView and UILabel at top below safe area.

Following is the way I create both UIImageView and UILabel

private var cardLbl: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textColor = .white
    label.text = "Hello User..."
    label.textAlignment = .center
    label.font = UIFont.preferredFont(style: .light, size: 14)
    label.accessibilityTraits = .header
    return label
}()

private var cardImg: UIImageView = {
    let imageView = UIImageView()
    imageView.backgroundColor = .red
    return imageView
}()

Then by using these methods I add them on view

private func setupCardArtImage(){
        view.addSubview(cardImg)
        NSLayoutConstraint.activate([
            cardImg.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            cardImg.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            cardImg.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
            cardImg.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            cardImg.heightAnchor.constraint(equalToConstant: 80),
            cardImg.widthAnchor.constraint(equalToConstant: 127)])
    }

and

private func setupCardArtName(){
        view.addSubview(cardLbl)
        NSLayoutConstraint.activate([
            cardLbl.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            cardLbl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            cardLbl.topAnchor.constraint(equalTo: cardImg.bottomAnchor, constant: 10),
            cardLbl.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            cardLbl.heightAnchor.constraint(equalToConstant: 30)])
    }

Problem I am facing is, I am able to add UILabel successfully, but I am not able to add UIImageView successfully.

Following images you can see that I am able to see UILabel at top, but when I call method to UIImageView I am not able to get it.

enter image description here

enter image description here

Can any one please help me to understand what I am doing wrong and guide me with solution. Thanks for help in advance.


Solution

  • All thanks to @Paulw11 who help me quickly to get the solution.

    Following is the code snippet with working solution.

    private func setupCardArtImage(){
            cardImg.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(cardImg)
            NSLayoutConstraint.activate([
                cardImg.centerXAnchor.constraint(equalTo: view.centerXAnchor),
                cardImg.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
                cardImg.heightAnchor.constraint(equalToConstant: 80),
                cardImg.widthAnchor.constraint(equalToConstant: 127)])
        }