Reputation: 65
I need help setting the correct constraints for the table view below. Heres the code for the constraints.. I am trying to show a 60 by 60 image view with a text by the right; please have a look at Tvtable view cell file.
Project link: https://github.com/lexypaul13/Trending-Tv-Shows/
private func set() {
addSubview(tvImage)
addSubview(tvName)
tvImage.translatesAutoresizingMaskIntoConstraints = false
tvName.translatesAutoresizingMaskIntoConstraints = false
let padding: CGFloat = 12
NSLayoutConstraint.activate([
tvImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
tvImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding),
tvImage.heightAnchor.constraint(equalToConstant: 60),
tvImage.widthAnchor.constraint(equalToConstant: 60),
tvName.centerYAnchor.constraint(equalTo: self.centerYAnchor),
tvName.leadingAnchor.constraint(equalTo: tvImage.trailingAnchor, constant: 24),
tvImage.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -padding),
tvImage.heightAnchor.constraint(equalToConstant: 40)])
}
Upvotes: 0
Views: 83
Reputation: 77690
Among other issues...
// add subviews to contentView, not self!
contentView.addSubview(tvImage)
contentView.addSubview(tvName)
tvImage.translatesAutoresizingMaskIntoConstraints = false
tvName.translatesAutoresizingMaskIntoConstraints = false
let padding: CGFloat = 12
NSLayoutConstraint.activate([
tvImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
tvImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding),
tvImage.heightAnchor.constraint(equalToConstant: 60),
tvImage.widthAnchor.constraint(equalToConstant: 60),
// constrain to contentView, not self!
//tvName.centerYAnchor.constraint(equalTo: self.centerYAnchor),
tvName.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
tvName.leadingAnchor.constraint(equalTo: tvImage.trailingAnchor, constant: 24),
// these two lines should be tvName, not tvImage!
//tvImage.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -padding),
//tvImage.heightAnchor.constraint(equalToConstant: 40)
tvName.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -padding),
tvName.heightAnchor.constraint(equalToConstant: 40)
])
Upvotes: 1
Reputation: 183
Your code:-
Here you added "tvImage" & "tvName" in tableviewCell.
addSubview(tvImage)
addSubview(tvName)
and setting the constraint with "contentView"(shown below)
tvImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
Solution:-
You just have to add "tvImage" & "tvName" in "tableviewCell's contentView"
contentView.addSubview(tvImage)
contentView.addSubview(tvName)
Upvotes: 1
Reputation: 10209
I think the first problem is that you should place the subviews of a table view cell into it's content view, so use:
self.contentView.addSubview(tvImage)
self.contentView.addSubview(tvName)
Upvotes: 1