У меня есть ячейка collectionView с меткой и imageView.ImageView находится в 8 точках от верхней части ячейки, верхняя часть метки находится в 8 точках от нижней части imageView, а нижняя часть ярлыка находится в 8 точках от нижней части ячейки.Метка переносится, когда она проходит на -10 пунктов от правого края ячейки.
Текст, который входит в метку, может занимать несколько строк.Я использую нижеприведенную функцию внутри sizeForItem
в collectionView для вычисления высоты метки:
func estimatedLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
let size = CGSize(width: width, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union([.usesLineFragmentOrigin, .usesFontLeading])
let attributes = [NSAttributedStringKey.font: font]
let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
return rectangleHeight
}
Ячейка расширяется правильно, но к метке добавлен дополнительный отступ, и я не могу понять, как избавиться от нее.из этого.
![enter image description here](https://i.stack.imgur.com/XPLEm.png)
Это многострочная метка размером 22, которая правильно упаковывается.Я сфотографировал это внутри 3D инспектора.Как вы можете заметить, в верхней и нижней части над и под текстом метки есть несколько дополнительных отступов.Интервал между 8 точками надписи под imageView является правильным, но дополнительный отступ делает его похожим на 24 точки.
Странно то, что даже когда я уменьшил размер метки до 16, дополнительный отступ все еще был там.
Как удалить это заполнение?
sizeForItem объекта collectionView, где вызывается оценочная функция LabelHeight:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let profileImageViewHeight: CGFloat = 50 // imageView height is set to 50 inside the cell
let padding: CGFloat = 24 // 8 x 8 x 8 the vertical padding inside the cell between the titleLabel, the imageView, and the cell
// estimatedLabelHeight is called here
let titleLabelHeight = estimatedLabelHeight(text: "some very very long text...", width: view.frame.width - 20, font: UIFont.systemFont(ofSize: 22))
let totalHeightOfCell = titleLabelHeight + profileImageViewHeight + padding
return CGSize(width: view.frame.width, height: totalHeightOfCell)
}
Ячейка:
class MyCell: UICollectionViewCell{
let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 22)
label.textColor = UIColor.black
label.textAlignment = .left
label.sizeToFit()
label.numberOfLines = 0
return label
}()
let profileImageView: UIImageView = {
// created it...
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(profileImageView)
addSubview(titleLabel)
profileImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true
profileImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
titleLabel.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 8).isActive = true
titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
titleLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true
// I tried to set the label's height using the below but the same padding issue occured
// let titleLabelHeight = estimatedLabelHeight(text: titleLabel.text!, width: self.frame.width - 20, font: UIFont.systemFont(ofSize: 22))
// titleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: titleLabelHeight).isActive = true
}
}