Reputation: 1304
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.
Can any one please help me to understand what I am doing wrong and guide me with solution. Thanks for help in advance.
Upvotes: 0
Views: 31
Reputation: 1304
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)])
}
Upvotes: 1