Не удалось получить флажок для одиночного выбора - PullRequest
0 голосов
/ 14 марта 2019

Я сделал ячейку просмотра таблицы, в которой есть кнопка. Я подключил IBAction кнопки в классе tableviewcell.swift. Затем я создал делегат и получил доступ к действию касания кнопки в классе viewcontroller следующим образом.

func optionTap(cell: SlideUpTableViewCell) {
    if let indexPath = tableview?.indexPath(for: cell) {
     }
}

Но я хочу, чтобы я хотел, чтобы за раз выбиралась только одна кнопка-флажок. У меня есть 3 ряда, и теперь я могу нажать на каждую из 3 кнопок, в то время как я хотел нажать только на 1 кнопку за раз. то есть, если я коснусь кнопки в 1-й ячейке, а затем коснусь кнопки во 2-й ячейке, то кнопка 1-й ячейки должна быть автоматически отменена. Короче, как работает нормальный одиночный выбор ...

Я пробовал это ... Но это не работает ...

   func optionTap(cell: SlideUpTableViewCell) {
if let indexPath = tableview?.indexPath(for: cell) {

  if selectedArrayIndex.contains(indexPath.row) {

    selectedArrayIndex.remove(at: selectedArrayIndex.index(of: indexPath.row)!)
    cell.checkBobButton.tintColor = ThemeManager.current().inactiveGrayColor
    cell.checkBobButton.setImage(UIImage(named: "circle_stroke"), for: .normal)

  } else {
    selectedArrayIndex.append(indexPath.row)
    cell.checkBobButton.tintColor = ThemeManager.current().secondaryColor
    cell.checkBobButton.setImage(UIImage(named: "circle_tick"), for: .normal)

  }

 }
}

РЕДАКТИРОВАТЬ 1: Это ячейка ForRow ..

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: SlideUpTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellID) as! SlideUpTableViewCell
    cell.delegate = self
    cell.selectionStyle = .none
    cell.headingLabel.text = self.arrData[indexPath.row].heading
    cell.subHeadingLabel.text = self.arrData[indexPath.row].subHeading

    return cell
  }

РЕДАКТИРОВАТЬ 2 Вот как будет выглядеть пользовательский интерфейс ..

enter image description here

Ответы [ 2 ]

1 голос
/ 14 марта 2019

Прежде всего вам не нужны действия кнопок.Следуйте приведенным ниже инструкциям для простого и безупречного кодирования:

  1. Возьмите переменную в вашем контроллере var selectedIndex = -1 // -1, если не выбран какой-либо индекс, если вы хотите выбрать любую опцию по умолчаниюзатем измените его соответствующим образом.

  2. Используйте tableView метод делегата didSelectRowAt indexPath

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    
        selectedIndex = indexPath.row
        myTblView.reloadData()
    
    }
    
  3. Теперь для переключения btn просто сделайте это в cellForRow.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Mycell
    
        :            
        cell.myBtn.isSelected = indexPath.row == selectedIndex
        :
    
        return cell
    }
    
  4. Теперь в раскадровке назначьте изображения кнопок для выбранного и состояния по умолчанию.

enter image description here

enter image description here

0 голосов
/ 14 марта 2019
 // if you want to use didselect or diddeselect than :

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          if let cell = tableView.cellForRow(at: indexPath)as? tableViewCell{
          cell.mRadioimage.image = UIImage(named: "radioCheckedImage")

            }
           }
   func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
          if let cell = tableView.cellForRow(at: indexPath)as? tableViewCell{
          cell.mRadioimage.image = UIImage(named: "radioUnCheckedImage")
              }       
          }

        // don't forget to choose singleSelection
        // hope its work for you
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...