Tôi đã đọc this question và nghĩ rằng tôi hiểu sự khác biệt giữa hai phương pháp cho đến khi tôi tìm thấy một ví dụ lạ:dequeueReusableCellWithIdentifier: forIndexPath: VS dequeueReusableCellWithIdentifier:
Set phong cách xem bảng tế bào của thể Basic, định danh được di động trong Storyboard, mã như sau:
import UIKit
class TableViewController: UITableViewController {
var items: [String]!
override func viewDidLoad() {
super.viewDidLoad()
items = ["first", "second", "third"]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// either works fine
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! // let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
}
Rất đơn giản, nhưng khi tôi thay đổi phương pháp tableView:cellForRowAtIndexPath:
-1, 2, 3, 4 trường hợp tương ứng:
Trường hợp 1:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
Trường hợp 2:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = items[indexPath.row]
return cell
}
Trường hợp 3:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
Trường hợp 4:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = items[indexPath.row]
return cell
}
Trường hợp 1, 2 (không hoạt động):
Trường hợp 3, 4 (chỉ hoạt động tốt):
Làm thế nào để giải thích? Tôi nghĩ rằng nó thực sự giúp hiểu hai phương pháp này từ góc nhìn khác, bất kỳ ý kiến nào đều được chào đón.
Câu trả lời của bạn là tuyệt vời, cảm ơn một bó! – fujianjin6471