我试图在调用 tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
方法之前向我的 tableview 添加一行。我尝试将其放入 viewDidLoad()
方法但没有成功,这可能吗?如何 ?
这是我的代码:
import UIKit
class CustomTestViewController : UITableViewController {
@IBOutlet var formDetailTableView: UITableView!
var data: Data?
var firstData: FirstData?
struct CurrentFormTableView {
struct CellIdentifiers {
static let MyCell = "MyCell"
static let MyFirstCell = "MyFirstCell"
}
}
override func viewDidLoad() {
super.viewDidLoad()
//HERE ADD THE FIRST ROW ?
let cell = tableView.dequeueReusableCellWithIdentifier(CurrentFormTableView.CellIdentifiers.MyFirstCell, forIndexPath: indexPath) as! MyFirstCell
cell.displayCell(firstData)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CurrentFormTableView.CellIdentifiers.MyCell, forIndexPath: indexPath) as! MyCell
cell.displayCell(data[indexPath.row])
return cell
}
}
最佳答案
如果我正确理解你的问题,这个问题很容易:)
无论数据数组中是否有数据,你总是希望在 tableView 中显示第一个单元格 :) 而你的问题是你不能将第一个对象添加到数据数组中,没关系,伙计:)
这是一个解决方案:)
不要在 ViewDidLoad 中做任何事情 :) 只需将第一行数据对象保存在局部变量中,比如:yourCustomObject
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : myTestCell = tableView.dequeueReusableCellWithIdentifier("testCell")! as! myTestCell
if indexPath.row == 0 {
cell.nameLabel.text = yourCustomObject.property
}
else {
cell.nameLabel.text = data[indexPath.row -1].property
}
return cell
}
问题解决了:)编码愉快:)
工作原理: 简单,
假设您的数据数组为空 :) 那么它将返回计数为 0 :) 但是您总是想显示您的第一个单元格不是吗 :) 所以将 +1 添加到数据数组计数 :) 返回数据.count + 1
现在在 cellForRowAtIndexPath
中仔细处理它。您不想最终访问第一个对象的数据数组中的数据,因此请检查索引路径 0。
而且您不希望最终访问数据索引之外的对象,因此请使用 data[indexPath.row -1]
希望我表达清楚了:)编码愉快
关于ios - 在渲染tableview swift 2之前添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916232/