Search code examples
iosuilabeluicollectionviewcellcenteringnslayoutconstraint

How to add constraints to a label inside of a UICollectionViewCell?


I have a UILabel

var cellTitle = UILabel()

I have a cellForItemAtIndexPath method where I declare a cell with the identifier and I add constraints to a label I created named cellTitle:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
    cellTitle = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 160))
    cellTitle.numberOfLines = 3
    cell.contentView.addSubview(cellTitle)
    cell.addConstraints([
        NSLayoutConstraint(item: cell, attribute: .CenterX, relatedBy: .Equal, toItem: cellTitle, attribute: .CenterX, multiplier: 1.0, constant: 0.0),
        NSLayoutConstraint(item: cell, attribute: .CenterY, relatedBy: .Equal, toItem: cellTitle, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
    ])
}

I get this error when I run the simulator:

Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) (

    "<NSLayoutConstraint:0x7baaac40 UICollectionViewCell:0x7b981570.centerY == UILabel:0x7baa3dd0'Towed by smaller boats, c...'.centerY>",
    "<NSAutoresizingMaskLayoutConstraint:0x7baa5c70 h=--& v=--& UILabel:0x7baa3dd0'Towed by smaller boats, c...'.midY == + 80>",
    "<NSLayoutConstraint:0x7baa5d50 'UIView-Encapsulated-Layout-Height' V:[UICollectionViewCell:0x7b981570(210)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x7bab1110 h=--- v=--- 'UIView-Encapsulated-Layout-Top' V:[UICollectionViewCell:0x7b981570]-(0)-|>"

)

Will attempt to recover by breaking constraint

In the part where I use the addConstraints method, I clearly am trying to center the label in the cell. For some reason the label isn't becoming centered in the cell:

containerView cells with label

What can I do to fix this? I appreciate any support.


Solution

  • Make sure the text in the label is aligned to the center. It appears to be aligned to the left, though the label itself is centered.

    cellLabel.textAlignment = NSTextAlignmentCenter;
    

    In swift it would be:

    cellLabel.textAlignment = NSTextAlignment.Center 
    

    Or just

    cellLabel.textAlignment = .center