来自NSURLSession的动态数据的单元格行的高度

时间:2014-09-25 11:12:09

标签: ios uitableview swift

我有动态单元格UITableView。在viewDidLoadNSURLSession将一些数据下载到公共变量someDataArray: [NSString]。我在我的单元格中使用AutoLayout和UILabel有this之类的约束。当加载视图时,我想看到所有单元格大小相同(例如:100)。但是当点击单元格时,我想将此单元格的高度更改为UIlabel帧的高度大小 所以我的代码看起来像:

class someVC: UIViewController, UITableViewDelegate
{
  var someDataArray: [NSString] = []
  var cellTapped = 0

  override func viewDidLoad() {
    //NSURLSession download to someDataArray[]
  }

  func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! 
  {
     let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC
     cell.someTextView.text = someDataArray[indexPath.row]
  }

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.table.cellForRowAtIndexPath(indexPath) as customCellVC

      if(cellTapped == 0) {
        cellTapped = 1
        table.beginUpdates()
        table.endUpdates()
      } else {
        cellTapped = 0
        table.beginUpdates()
        table.endUpdates()
      }
    }

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

   // heightForRowAtIndexPath call first, how to calculate the size of frame uilabel? When it's tapped or not
   // how to make all UILabel one size by load but sizetofit by tap on it?
 }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Autolayout来计算行的高度。看看这个:

https://github.com/smileyborg/TableViewCellWithAutoLayoutiOS8

或者:(所以我解决了这个,因为它更符合我的要求)是:

计算标签的高度:

func getLabelHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {

    let font = UIFont.systemFontOfSize(fontSize)
    let size = CGSizeMake(width,CGFloat.max)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .ByWordWrapping;
    let attributes = [NSFontAttributeName:font,
        NSParagraphStyleAttributeName:paragraphStyle.copy()]

    var text = mytext as NSString
    let rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context:nil)
    return rect.size.height
}

这将返回特定宽度的标签的计算高度。你可以在ViewDidLoad上计算这个(第一次将它设置为一个以Indexpath.row为索引的字典),然后将这些值用于“heightForRowAtIndexPath”。因此,您也可以重新加载特定的单元格(使用新的高度)

然后您仍然可以使用“SizeToFit”宽度作为特定标签宽度。

相关问题