所以我在 UICollectionView 中有一个单元格
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: myCell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! myCell
// cell.descrption is an UILabel
cell.description.text = newText
return cell
}
和
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(collectionView.bounds.width*0.95, collectionView.bounds.height/4)
}
我的问题是:
newText
是从网络上获取的。所以它是动态变化的。单元格的文本设置为 newText 后,我应该如何调整标签以使其具有适合“newText”的正确大小以及我应该如何调整单元格的大小并在屏幕上显示它?
我注意到 sizeForItemAtIndexPath()
在 cellForItemAtIndexPath()
之前被调用。因此,我无法在 sizeForItemAtIndexPath()
中计算 nextText 的大小。
最佳答案
这是检查 sizeForItemAtIndexPath()
中文本大小的好方法,
因为您已经知道 sizeForItemAtIndexPath()
在 cellForItemAtIndexPath()
之前被调用,您可以拥有一个具有相同信息的虚拟单元格。例如,您可以引用我在UITableView
中使用的代码,并根据您的要求实现。
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
var myLabel:UILabel!
var labelText = myTextArray[indexPath.row]
var constraint = CGSizeMake(662, MAXFLOAT);
var attributes = NSDictionary(dictionary: [UIFont(descriptor: UIFontDescriptorSizeAttribute, size: 12):NSFontAttributeName])
var textSize:CGRect = NSString(string: labelText).boundingRectWithSize(constraint, options: NSStringDrawingUsesLineFragmentOrigin, attributes: attributes, context: nil)
myLabel.text = labelText
return myLabel.frame.size.height
}
您可以在 UICollectionView
中执行相同的操作以实现大小,因为两者共享相同的继承。
所以不会有问题。
甚至您也可以根据文本中的字符数返回自定义高度。喜欢
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
var myLabel:UILabel!
var labelText = myTextArray[indexPath.row]
if count(labelText) > 0 && count(labelText) <30
return 40;
else if count(labelText)>31 && count(labelText)<60
return 70;
//and so on
}
关于iOS - 如何在标签文本更改后动态更新 UICollectionViewCell 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771515/