2016-08-26 49 views
0

我在我的一些单元格在tableview中添加额外的标签时遇到问题。此刻,我确定的rowHeight如下:在UITableViewCell中以编程方式添加标签?

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     let numberOfBusses = nearbyStops[indexPath.section].getDepartures()[indexPath.row]!.count 
     if (numberOfBusses > 2) { 
      return CGFloat((75/2) * numberOfBusses) 
     } else { 
      return 75 
     } 
} 

我尝试这样做是为了添加缺少的标签,但没有任何反应:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! BusDepartureTableViewCell 
    let numberOfBusses = nearbyStops[indexPath.section].getDepartures()[indexPath.row]!.count 
      if (numberOfBusses > 2) { 
       var label = UILabel(frame: CGRectMake(0, 0, 200, 21)) 
       label.center = CGPointMake(160, 284) 
       label.textAlignment = NSTextAlignment.Center 
       label.text = "I'am a test label" 
       label.textColor = UIColor.redColor() 
       cell.foregroundView.addSubview(label) 
      } 


......... 

我在做什么错?

UPDATE:

我已经采取了我目前的成就的图片,我已经得到了,不过细胞扩展,你可以看到,现在有空间供其他两个标签,但我怎么加他们?

enter image description here

+1

我不会在一个UITableViewCell因为细胞被重新使用添加这样的一个自定义的UIView。检查'cell.foregroudView'和'label'的框架。 – Larme

+0

你会怎么做?我有点迷失在如何去做不同。 – Recusiwe

+1

我会把'BusDepartureTableViewCell'(xib)的视图,并在必要时隐藏它。 – Larme

回答

0

细胞获得重新“拿来主义” - 这意味着,以节省内存的iOS使用您的UI元素科技只是作为一个占位符,并设置自己的价值观

cellForRowAtIndexPath 

在这种情况下,它多在故事板中创建2个(或更多)不同的单元格布局的更高内存效率,并为每个单元格提供不同的标识符。

例如:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let item = yourPopulatingArray[indexPath.row] as Item 

    var cellIdentifier = "cellLayout1" 

    if item.anyPropertyToCheckforLayout { 
     cellIdentifier = "cellLayout2" 
    } 

    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! BusDepartureTableViewCell 
+0

哦,我明白了,所以你只需要有几个不同的调用布局。所以我只是在我的if语句中交换cellIndentifiers? – Recusiwe

+0

是的,这是做这种事情的最佳方式 – derdida

+0

你会在.xib或?我只是习惯使用故事板。 – Recusiwe

相关问题