gpt4 book ai didi

swift:增加 TableViewCell 高度取决于 UILabel 而不使用约束

转载 作者:行者123 更新时间:2023-11-30 13:08:49 25 4
gpt4 key购买 nike

我想增加 UITableviewCell 高度取决于 TableViewCell 按钮单击上的 UILabel 内容。我对此进行了搜索,但我找到了有关限制的答案。

我想动态增加 UITabelViewCell 高度,而不使用“Constarints”/自动布局。

我使用以下代码获取标签高度:

func getLabelHeight(lbl : UILabel) -> CGFloat
{
let constraint = CGSizeMake(lbl.frame.size.width, CGFloat.max)
var size = CGSize()

let context = NSStringDrawingContext();

let boundingBox : CGSize

boundingBox = NSString(string: lbl.text!).boundingRectWithSize(constraint,
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: self],
context: context).size

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height))
return size.height;
}

但我无法在 UITableview 中使用此代码。为了增加 TableViewCell 高度,我编写了以下代码:

func btnReadMoreClick(sender: UIButton){
let buttonTag = sender.tag

indexOfReadMoreButton = sender.tag
isReadMoreButtonTouched = true

tableVDetail.beginUpdates()
tableVDetail.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfReadMoreButton, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
tableVDetail.endUpdates()
}

并设置单元格高度

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

但是使用这个我无法得到我的输出。 :(

提前致谢!

最佳答案

如果您对单元设置了正确的约束,它应该完成其余的工作。

它是一个助手,可以自动调整单元格大小并计算预期高度。

extension UITableViewCell {
func calcualteHeight(inTableview tableview: UITableView) -> CGFloat {
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
self.bounds = CGRectMake(0, 0, CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(self.bounds))
self.setNeedsLayout()
self.layoutIfNeeded()

let height = self.contentView.systemLayoutSizeFittingSize(self.bounds.size, withHorizontalFittingPriority: UILayoutPriorityFittingSizeLevel, verticalFittingPriority: UILayoutPriorityFittingSizeLevel).height
return height
}
}

在 TableView 委托(delegate)中,获取计算单元格并填充数据。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell = tableView.dequeueReusableCellWithIdentifier(self.viewModel.reuseIdentifier(atIndexPath: indexPath)) as! YourCell
cell.setupData(fillCellYourData)
return cell.calcualteHeight(inTableview: tableView)
}

关于swift:增加 TableViewCell 高度取决于 UILabel 而不使用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com