在我的单元格中,我具有标题标签和描述标签。说明标签可以大小不一。我用它descriptionLabel.sizeToFit()
,但是如何在单元格中使用它。如果cell.sizeToFit()不起作用
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ExercisesCollectionViewCell
let workouts = exercises[indexPath.item]
cell.titleLabel.text = workouts.titleExercise
cell.descriptionLabel.text = workouts.descriptionExercise
cell.descriptionLabel.sizeToFit()
cell.sizeToFit()
return cell
}
答案 0 :(得分:-1)
使用UITableview代替UICollectionView
首先,您必须计算UILabel的行数
NSInteger lineCount = 0;
CGSize textSize = CGSizeMake(yourLabel.frame.size.width, MAXFLOAT);
int rHeight = lroundf([yourLabel sizeThatFits:textSize].height);
int charSize = lroundf(yourLabel.font.lineHeight);
lineCount = rHeight/charSize;
NSLog(@"No of lines: %i",lineCount);
否则,您可以扩展以计算标签的最大行数
extension UILabel {
func calculateMaxLines() -> Int {
let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity))
let charSize = font.lineHeight
let text = (self.text ?? "") as NSString
let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
let linesRoundedUp = Int(ceil(textSize.height/charSize))
return linesRoundedUp
}
}
使用它:
let lineCount = YourLabel. calculateMaxLines
现在设置标签每一行的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return lineCount * 18 //If total 3 line so 3*18 = 54 is height else you can take any number instead of 18 according to font size height
}