简体   繁体   中英

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.

在此处输入图片说明 在此处输入图片说明


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

在此处输入图片说明 在此处输入图片说明


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.

Simplest method is just set label lines as 0

在此处输入图片说明

@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
        }

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM