обновить ячейку в табличном представлении - PullRequest
0 голосов
/ 11 ноября 2018

Мой код читает массив городов в tableView.

  • Когда ячейка щелкается, она перемещается на SecondViewController. У SecondViewController есть кнопка.

  • Если я нажму кнопку, она отобразит изображение в этой ячейке.

Проблема: Я пытаюсь обновить ячейку при каждом нажатии кнопки. Он работает, но независимо от того, в какой ячейке щелкают, он всегда отображает изображение для ячейки 3, а если я нажал еще раз, он отображает изображение для ячейки № 1.

Как это исправить, чтобы при нажатии кнопки отображалось изображение ее ячейки, а если щелкается та же ячейка, скрывайте изображение.

Мои коды:

var first = 0
var reload = false
var cellNumber: Int!

var cities:[String] = ["paris", "moscow", "milan","rome","madrid","garda","barcelona"]

@IBOutlet weak var tableView: UITableView!
// func to reload a cell
@objc func toReload(rowNumber: Int){
    reload = true

    let indexPath = IndexPath(row: rowNumber , section: 0)
    tableView.reloadRows(at: [indexPath], with: .none)
}

// load tableview from a SecondViewController call
@objc func loadList(notification: NSNotification){

    self.tableView.reloadData() // reload tableview
    toReload(rowNumber: cellNumber)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cities.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell

    cell.label1.text = cities[indexPath.row]

    let image : UIImage = UIImage(named: "20870718")! // assign imageView to an image

    if first == 0 {
       cell.myimage.isHidden = true // hide image
        first = 1 // condition to never enter again
    }

    if reload == true {

        if cell.myimage.isHidden == true {
             cell.myimage.image = image
             cell.myimage.isHidden = false
        }
        else{
            cell.myimage.isHidden = true
        }
        reload = false

    }

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.cellNumber = indexPath.row

    performSegue(withIdentifier: "send", sender: self)
}


override func viewDidLoad() {
    super.viewDidLoad()
    tableView.reloadData()

     NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
    // call load list method
}

}

SecondViewController:

@IBAction func displayImage(_ sender: Any) {

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)

}

1 Ответ

0 голосов
/ 11 ноября 2018

В вашем cellForRowAt есть проблема. Когда secondViewController уведомляет первый, независимо от того, какую ячейку вы перезагружаете, всегда будет вызываться cellForRowAt, потому что когда вы прокручиваете tableView, требуется отменить ячейку, и reload == true становится истинным для всех ячейки. так что вы должны проверить, если indexPath.row == cellNumber, тогда сделайте все остальное:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomCell
   cell.label1.text = cities[indexPath.row]
   let image : UIImage = UIImage(named: "20870718")! // assign imageView to an image
   if first == 0 {
      cell.myimage.isHidden = true // hide image
      first = 1 // condition to never enter again
   }
   if indexPath.row == cellNumber {
     if reload == true {
        if cell.myimage.isHidden == true {
          cell.myimage.image = image
          cell.myimage.isHidden = false
        }
        else {
            cell.myimage.isHidden = true
        }
        reload = false
      }
   }
   return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...