Повторялось на двух проектах и искалось напрасно, поэтому я надеюсь, что кто-то может помочь ...Swift 3 tableViewCell Button, странное поведение, отправьте одну кнопку и другие те же изменения ячеек?
Создал базовый TableViewController и один TableViewCell. Запустите и нажмите первую кнопку, прокрутите вниз, а другие случайные кнопки также показывают одно и то же изменение?
TableViewController
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 99
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonCell", for: indexPath) as! ButtonCell
cell.rowLabel.text = "\(indexPath.row)"
cell.tapAction = { (cell) in
self.showAlertForRow(tableView.indexPath(for: cell)!.row)
}
return cell
}
// MARK: - Extracted method
func showAlertForRow(_ row: Int) {
let alert = UIAlertController(
title: "BEHOLD",
message: "Cell at row \(row) was tapped!",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Gotcha!", style: UIAlertActionStyle.default, handler: { (test) -> Void in
self.dismiss(animated: true, completion: nil)
}))
self.present(
alert,
animated: true,
completion: nil)
}
}
Table View Cell
// ButtonCell.swift
import UIKit
class ButtonCell: UITableViewCell {
var tapAction: ((UITableViewCell) -> Void)?
@IBOutlet weak var rowLabel: UILabel!
@IBOutlet weak var button: UIButton!
@IBAction func buttonTap(_ sender: AnyObject) {
button.setTitle("Correct", for: .normal)
tapAction?(self)
}
}
Я не думаю, что ему нужен метод 'createCell()', так как он может использовать метод 'readyForReuse()', предоставляемый Apple. –
его подход, но если он хочет изменить данные, он может создать «createCell (withItem: Item)» и добавить элемент непосредственно в ячейку. Вы можете делать все, что захотите, и ваш метод cellForRowAt не заполнен кодом – alecnash