当 UILabel 尾随时自动布局被破坏
Autolayout is broken when UILabel given trailing
如果我不提供尾随属性,它工作正常。
但是,如果文字较长,则会被截屏。
所以我设置了尾随。
但是,这会破坏 UICollectionViewCell 的宽度。
这是我的代码
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width
return CGSize(width: width / 2, height: 53)
}
这是为什么?请帮助我。
最简单的方法就是将标签行设为0
@oddK - 不要将宽度设置为集合宽度/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
}
如果我不提供尾随属性,它工作正常。
但是,如果文字较长,则会被截屏。
所以我设置了尾随。
但是,这会破坏 UICollectionViewCell 的宽度。
这是我的代码
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width
return CGSize(width: width / 2, height: 53)
}
这是为什么?请帮助我。
最简单的方法就是将标签行设为0
@oddK - 不要将宽度设置为集合宽度/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
}