Autolayout не работает, когда UILabel задал трейлинг - PullRequest
0 голосов
/ 19 марта 2020

Работает нормально, если я не задаю конечные свойства.
Однако, если текст длинный, он будет обрезан по экрану.

enter image description here enter image description here


Итак, я установил трейлинг.
Но это нарушит ширину UICollectionViewCell.

enter image description here enter image description here


Это мой код

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

Почему это так? Пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 19 марта 2020

Самый простой метод - просто установить линии меток как 0

enter image description here

@ oddK - Не устанавливать ширину как коллекцию width / 2, вместо этого установите ширину, основываясь на текстовом содержимом,

  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

...