Hi, I have added a UILabel
to my collection view cell programmatically and have set up constraints using auto layout. The centerX
and centerY
constraints of the label are equal to the centerX
and centerY
anchors of the content view. However, the label is appearing in the top left corner of the cell rather than in the center where I expect it to be.
Here is my code:
protocol TapLabelCollectionViewCellDelegate: AnyObject {
func incrementNumberOfTaps(index: Int)
}
class TapLabelCollectionViewCell: UICollectionViewCell {
var taplabel: UILabel!
var delegate: TapLabelCollectionViewCellDelegate?
var index: Int!
static let identifier = "tapLabelCellIdentifier"
override init(frame: CGRect) {
super.init(frame: frame)
taplabel = UILabel()
taplabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(taplabel)
NSLayoutConstraint.activate([
taplabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
taplabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
])
setUpTapGestureRecognizer()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setUpTapGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(incrementNumberOfTaps))
print("tap Label,", taplabel)
taplabel.addGestureRecognizer(tapGestureRecognizer)
}
@objc func incrementNumberOfTaps() {
delegate?.incrementNumberOfTaps(index: index)
}
}
I am also getting the following warning in Xcode