我有一個待辦事項列表,我有一個標籤和一個按鈕在同一個單元格中,當我單擊按鈕時,更改該單元格的圖像按鈕,但是當我滾動表格視圖時,其他單元格上出現相同的按鈕,它沒有出現在單元格中,按鈕沒有被按下。爲什麼我的Tableview重用了一些單元格?
這裏是我的cellForRowAtIndexPath代碼
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! TaskTableViewCell
cell.label.text = "Task Number: \(indexPath.row + 1)"
cell.btnFavorite.setImage(UIImage(named: "star"), forState: .Normal)
cell.btnFavorite.setImage(UIImage(named: "star-filled"), forState: .Selected)
cell.btnFavorite.addTarget(self, action: #selector(ListOfTasksViewController.addRemoveFavoriteList), forControlEvents: .TouchUpInside)
return cell
}
func addRemoveFavoriteList(sender : UIButton) {
sender.selected = !sender.selected
}
定製TableViewCell類:
import UIKit
class TaskTableViewCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var btnFavorite: FavoriteButton!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
label.text = nil
btnFavorite.selected = false
}
}
視圖控制器:
import UIKit
class ListOfTasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! TaskTableViewCell
cell.label.text = "Task Number: \(indexPath.row + 1)"
cell.btnFavorite.indexPath = indexPath.row
cell.btnFavorite.addTarget(self, action: #selector(ListOfTasksViewController.addRemoveFavoriteList), forControlEvents: .TouchUpInside)
return cell
}
func addRemoveFavoriteList(sender : FavoriteButton) {
if sender.selected {
sender.selected = false
} else {
sender.selected = true
let index = NSIndexPath(forRow: sender.indexPath, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(index) as! TaskTableViewCell
}
}
}
這不是一個 「問題」。重用是正確的和理想的行爲。畢竟,當你說'tableView.dequeueReusableCellWithIdentifier'時,你買了它;你在說什麼? – matt
當您按下單元格上的按鈕時,您需要更新您的數據源。 –