Search code examples
iosswiftuicollectionviewuilabel

Autolayout is broken when UILabel given trailing


It works fine if I don't give trailing properties.
However, if the text is long, it will be cut off the screen.

enter image description here enter image description here


So I set trailing.
But, this will break the width of the UICollectionViewCell.

enter image description here enter image description here


This is my code

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.frame.width
    return CGSize(width: width / 2, height: 53)
}

Why is that? Please help me.


Solution

  • Simplest method is just set label lines as 0

    enter image description here

    @oddK - Don't set the width as collection width / 2, instead set the width based on the text content,

      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let width = collectionView.frame.width
            let lblWidth = "My text".getWidth(withConstrainedHeight: CGFloat(53), font: UIFont.systemFont(ofSize: 14))
    
            return CGSize(width: lblWidth, height: 53)
        }
    
    
    
        //Get Width of content in label
            func getWidth(withConstrainedHeight:CGFloat, font: UIFont) -> CGFloat {
                let viewRect = CGSize(width: .greatestFiniteMagnitude, height: withConstrainedHeight)
                let getFrame = self.boundingRect(with: viewRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)
                return getFrame.size.width
            }
    

    enter image description here