2017-02-16 9 views
-1

Повторялось на двух проектах и ​​искалось напрасно, поэтому я надеюсь, что кто-то может помочь ...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) 



    } 
} 

ответ

0

Давайте начнем с основ. Вам не нужно это:

cell.tapAction = { (cell) in 
     self.showAlertForRow(tableView.indexPath(for: cell)!.row) 
    } 

Лучше использовать рамки яблока:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     showAlertForRow(indexPath.row) 
    } 

Второй метод создания в вас клеток как

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) 
    } 

    func createCell() { 
     button.setTitle("Your button title", for: normal) 
    } 
} 

и вызвать метод createCell в вашем

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    ... 
    cell.createCell() 
    ... 

} 

Надежда I может помочь, но попытайтесь начать с основ: https://developer.apple.com/reference/uikit/uitableviewdelegate

+0

Я не думаю, что ему нужен метод 'createCell()', так как он может использовать метод 'readyForReuse()', предоставляемый Apple. –

+0

его подход, но если он хочет изменить данные, он может создать «createCell (withItem: Item)» и добавить элемент непосредственно в ячейку. Вы можете делать все, что захотите, и ваш метод cellForRowAt не заполнен кодом – alecnash

0

Это происходит потому, что вы ваш UITableViewCells извлечение из. Чтобы решить проблему, вы должны использовать метод prepareForReuse() в своем ButtonCell. Вы можете сохранить состояния всех ваших кнопок, и когда ячейка будет удалена, вы можете просто установить заголовок кнопки в этой ячейке в методе prepareForReuse().