Ячейка табличного представления выбрана - PullRequest
0 голосов
/ 04 декабря 2018

Я использую TableView с выбранной кнопкой, у меня проблема с кодом, потому что, когда кнопка выбрана, я не знаю, что такое IndexPath моей ячейки.

Я использую ячейку файла TableView с табличным представлением cell.xib

@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var lbDetail: UILabel!
@IBOutlet weak var btnCheckMark: UIButton!
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

В моем контроллере View у меня есть это:

  override func viewDidLoad() {
    super.viewDidLoad()
    self.topBar.rightBarButtonItem = UIBarButtonItem(title: "Apply", style: .done, target: self, action: #selector(self.apply))
    self.topBar.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "backButton"), style: .done, target: self, action: #selector(backHome))
    listeView.register(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "CheckList")
    listeView.dataSource = self
    listeView.delegate = self
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //let rowpath = indexPath.row
    let cell = tableView.dequeueReusableCell(withIdentifier: "CheckList") as! TableViewCell
    cell.lbTitle.text = "\(self.deviceData[indexPath.row].brandName) \(self.deviceData[indexPath.row].modelName)"
    cell.lbDetail.text = "\(self.deviceData[indexPath.row].operatorName) \(self.deviceData[indexPath.row].version), \(self.deviceData[indexPath.row].browserName) \(self.deviceData[indexPath.row].version)"
    //cell.selectionStyle = .none
    cell.btnCheckMark.addTarget(self, action: #selector(checkMarkButton(sender:)), for: .touchUpInside)
    return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath.row)
    let test = TableViewCell()
    test.lbTitle.text = "11"

}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 71.0
}
@objc func checkMarkButton(sender: UIButton) {
    if sender.isSelected {
        sender.isSelected = false
        nb -= 1
        //rint(paramaters)
    } else {
        sender.isSelected = true
        paramaters["devicesList[\(nb)][deviceId]"] = id
        nb += 1
    }
    print(paramaters)
}

В моей функции checkMarkButton, яхочу знать indexPath.row

Ответы [ 4 ]

0 голосов
/ 04 декабря 2018

Это неправильный способ сделать это. Вместо этого попробуйте использовать делегатскую функцию didSelectRowAt и обновите данные, например:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        data[indexPath.row].selected = !data[indexPath.row].selected
        tableView.reloadRows(at: [indexPath], with: .none)
    }

    //then on the cellForRowAt:
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "CheckList") as! TableViewCell
     cell.lbTitle.text = "\(self.deviceData[indexPath.row].brandName) \(self.deviceData[indexPath.row].modelName)"
     cell.lbDetail.text = "\(self.deviceData[indexPath.row].operatorName) \(self.deviceData[indexPath.row].version), \(self.deviceData[indexPath.row].browserName) \(self.deviceData[indexPath.row].version)"
    //cell.selectionStyle = .none
     cell.setSelected(data[indexPath.row].selected, animated: true)
     return cell
    }

, чтобы синхронизировать tableView и ваши данные.

0 голосов
/ 04 декабря 2018

Используйте tableView.indexPath(for: UITableViewCell), чтобы получить весь IndexPath для вашей ячейки.

Пример использования:

@objc func checkMarkButton(sender: UIButton) {
    // do something else

    guard let cell = sender.superview as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else {
        return
    }

    print(indexPath.row)
}

Используйте if let вместо guard let, если вы не хотитепрекратить выполнение.

0 голосов
/ 04 декабря 2018

В Swift наиболее эффективным способом является закрытие обратного вызова .

Это довольно просто: нет протоколов, нет цели / действия, нет делегата, нет тегов, нет путей к индексам, нет представленияматематика, атрибут @objc.

  • В модель , представляющую deviceData, добавьте свойство isSelected

    var isSelected = false
    
  • В ячейку добавьте свойство callback и IBAction.Подключите кнопку к IBActionIBAction состояние выбора переключается, и обратный вызов называется

    var callback : ((UIButton) -> Void))?
    
    @IBAction func buttonPressed(_ sender : UIButton) {
       sender.isSelected.toggle()
       callback?(sender)
    }
    
  • В контроллере представления устанавливается и обрабатывается обратный вызов в cellForRow

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //let rowpath = indexPath.row
        let cell = tableView.dequeueReusableCell(withIdentifier: "CheckList") as! TableViewCell
        let data = self.deviceData[indexPath.row]
        cell.lbTitle.text = "\(data.brandName) \(data.modelName)"
        cell.lbDetail.text = "\(data.operatorName) \(data.version), \(data.browserName) \(data.version)"
        cell.btnCheckMark.isSelected = data.isSelected
        cell.callback { button in 
             self.deviceData[indexPath.row].isSelected = button.isSelected
             // or if deviceData is a class with reference semantics
             // data.isSelected = button.isSelected
        }
        return cell
    }
    
0 голосов
/ 04 декабря 2018

Вы можете создать подкласс для кнопки со свойством Indexpath и использовать эту кнопку вместо этого.

Итак:

class ButtonWithIndexPath : UIButton {
    var indexPath:IndexPath?
}

Затем назначьте это свойство новой кнопке в методе cellforRowAt вашей таблицы.при назначении всех остальных свойств.

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