2015-09-04 57 views
1

在我的iOS应用程序中,有一个静态单元格的表格视图控制器,其中包含三种不同类型的单元格,其样式为字幕。其中一个应该比另外两个高得多,因为它应该包含很长的文本。因此,在其大小检查器中,我将高度设置为100,但是当我通过其标识符在代码中创建新单元格时,高度始终是默认单元格。Swift/XCode 6.4:如何以编程方式更改表格视图控制器中单元格的高度

我该如何改变它?我读过,我应该重写此方法:

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

     return 100 //Whatever fits your need for that cell 
} 

但我不知道如何使用它。你能解释一下吗? enter image description here

+0

可能重复的高度[的tableView细胞高度...如何定制呢?](http://stackoverflow.com/questions/3737218/tableview-cell-height-how - 定制它) –

回答

7

正如你说,你tableview细胞是静态,所以你知道哪个小区有更多的高度,传递heightForRowAtIndexPath该小区的indexpath并从那里返回单元格的预期高度。 假设你的第一小区是有更多的高度,然后用heightForRowAtIndexPath这样

func tableView(tableView: UITableView, 
    heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     if indexPath.row == 1 { 
      return 100 //Whatever fits your need for that cell 
     } else { 
      return 50 // other cell height 
     } 
} 

无需创建三个不同的原型细胞,刚刚创建的细胞,这将是足够的。

+0

哦,它的工作原理,谢谢。但为什么我不能通过故事板设置它?这会容易得多...原谅我的无知,我对ios和xcode以及swift很陌生。请解释一下,如果你想 – user1576208

+0

你在你的代码中使用'heightForRowAtIndexPath'。 – Rajat

+0

是的,我刚刚使用它,它的工作原理......我只是想知道为什么设置故事板是不够的,为什么还需要在您的cellForRowAtIndexPath中使用 – user1576208

0

为什么不在界面构建器中使用2个不同的TableViewCells并在cellForRowAtIndexPath中选择正确的一个?

这是最简单的方法,您可以在必要时区分两种类型之间的差异。

+0

Ehm,这就是我所做的。看看我的问题,我已经上传了截图。我有3个不同的TableViewCells ...最后一个更大,但它完全被忽略。我想我错过了故事板中的一些设置...或者可能是一些愚蠢的错误。是对的? – user1576208

+0

你使用的是正确的原型单元吗?你可能每次加载相同的一个 – Glenn

+0

我认为是因为我用正确的标识符来调用它。或者你的意思是什么? – user1576208

2

您可以执行heightForRowAtIndexPath,正如您在文章中提到的,并获取cellForRowAtIndexPath的单元格。然后设置为根据的reuseIdentifier

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
    if cell.reuseIdentifier == "SpecialCell" { 
     return 100.0 
    } 
    } 
    return 44.0 
} 
相关问题