проблема представления таблицы, indexPath - ноль - PullRequest
0 голосов
/ 27 августа 2018

У меня есть кнопка и метка в табличном представлении (я использую 8 строк) и по какой-то причине, когда я нажимаю первую кнопку, я получаю ошибку indexPath nil, но когда я нажимаю вторую кнопку (2-я строка), я получаюметка первого ряда.Когда я нажимаю кнопку 3-й строки, я получаю метку второй строки и т. Д. Почему они не выровнены.Я хочу, чтобы при нажатии на кнопку первой строки, чтобы получить метку первой строки и т. Д., Пожалуйста, см. Код ниже.Спасибо !!

   @objc func btnAction(_ sender: AnyObject) {


    var position: CGPoint = sender.convert(.zero, to: self.table)

    print (position)
    let indexPath = self.table.indexPathForRow(at: position)
    print (indexPath?.row)
    let cell: UITableViewCell = table.cellForRow(at: indexPath!)! as
    UITableViewCell


      print (indexPath?.row)
    print (currentAnimalArray[(indexPath?.row)!].name)
    GlobalVariable.addedExercises.append(currentAnimalArray[(indexPath?.row)!].name)

}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? TableCell else {return UITableViewCell() }

   // print(indexPath)

    cell.nameLbl.text=currentAnimalArray[indexPath.row].name
 // print("\(#function) --- section = \(indexPath.section), row = \(indexPath.row)")

   // print (currentAnimalArray[indexPath.row].name)

    cell.b.tag = indexPath.row

   // print (indexPath.row)
    cell.b.addTarget(self, action: #selector(SecondVC.btnAction(_:)), for: .touchUpInside)


    return cell



}

Ответы [ 2 ]

0 голосов
/ 27 августа 2018

Вы уже передаете indexPath.row с тегом кнопки.Используйте тег в качестве индекса просто

@objc func btnAction(_ sender: UIButton) { 
    GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
} 
0 голосов
/ 27 августа 2018

Frame math - худший вариант, если у вас нет выбора.Здесь у вас есть много вариантов выбора.

Например, почему бы вам не использовать tag, назначенный кнопке?

@objc func btnAction(_ sender: UIButton) {
    GlobalVariable.addedExercises.append(currentAnimalArray[sender.tag].name)
}

A swiftier и более эффективное решение - закрытие обратного вызова:

В TableCell добавьте действие кнопки и свойство callback.Розетка не нужна.Отключите розетку и подключите кнопку к действию в Интерфейсном Разработчике.При нажатии кнопки вызывается обратный вызов.

class TableCell: UITableViewCell {

    // @IBOutlet var b : UIButton!
    @IBOutlet var nameLbl : UILabel!

    var callback : (()->())?

    @IBAction func btnAction(_ sender: UIButton) {
        callback?()
    }
}

Удалите действие кнопки в контроллере.

В cellForRow назначьте закрытие для свойства callback

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // no guard, the code must not crash. If it does you made a design mistake
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableCell

    let animal = currentAnimalArray[indexPath.row]
    cell.nameLbl.text = animal.name

    cell.callback = {
         GlobalVariable.addedExercises.append(animal.name)
    }

    return cell
}

Вы видите, что путь индекса вообще не нужен.Объект animal захвачен в замыкании.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...