我有一个 NSMutableArray (array2) 作为 TableView 的数据源。当我选择 searchResultsTableView 的一个单元格并使用该数组重新加载 self.tableView 时,我想将对象添加到该数组。
如果我使用 array2.addObject() 方法添加对象,那么所有单元格都可以使用单独的数据。
但是,如果我使用 array2.insertObject(myObject, atIndex: 0) 添加对象,则所有单元格显示的数据与 array2[0] 的数据相同。为什么 ?
我的问题出在 TableView 的 didSelectRowAtIndexPath 函数中。我总是想在我的 TableView 的第一个位置添加选定的对象,这就是为什么我用 insertObject 方法而不是 addObject 方法实现的原因。下面是我的代码部分。
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.array1.count
}else{
return self.array2.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if tableView == self.searchDisplayController!.searchResultsTableView {
let number = self.array1[indexPath.row]
cell.textLabel?.text = String(number)
} else {
let cell: customCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as customCell
let brand = self.array2[indexPath.row] as NSString
cell.name.text = brand
cell.comment.text = "100"
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.searchDisplayController!.searchResultsTableView {
let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
self.array2.insertObject(cell.textLabel!.text!, atIndex: 0)
//self.array2.addObject(cell.textLabel!.text!)
self.searchDisplayController!.setActive(false, animated: true)
self.tableView.reloadData()
}
}
最佳答案
你的 cellForRowAtIndexPath 方法很奇怪!...你总是返回“let cell = UITableViewCell()”而不是实际上你的出队“cell”
将您的方法更改为:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.searchDisplayController!.searchResultsTableView {
let number = self.array1[indexPath.row]
let cell = UITableViewCell()
cell.textLabel?.text = String(number)
return cell
} else {
let cell: customCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as customCell
let brand = self.array2[indexPath.row] as NSString
cell.name.text = brand
cell.comment.text = "100"
return cell
}
}
关于uitableview - 表格单元格快速显示 NSMutableArray 的第一个索引数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428996/