Как быстро управлять двумя кнопками в одной и той же ячейке таблицы? - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь управлять двумя кнопками в одной настраиваемой ячейке таблицы. Добавлены две кнопки с именами Да и Нет. Если выбрана кнопка «Да», кнопка «Нет» будет неактивной, а кнопка «Да» стала активной.

Вот изображение, которое мне нужно

enter image description here

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell") as! TableViewCell
    cell.yesButton.tag = 101
    cell.noButton.tag = 102
    cell.yesButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
    cell.noButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: UIControl.Event.touchUpInside)
    return cell
}

 @objc func buttonClicked(sender: AnyObject) {
    let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: tableList)
    let indexPath = tableList.indexPathForRow(at: buttonPosition)
    if sender.tag == 101 {
        if indexPath != nil {
            print("Cell indexpath = \(String(describing: indexPath?.row))")
        }
    }

    if sender.tag == 102 {
        if indexPath != nil {
            print("Cell indexpath = \(String(describing: indexPath?.row))")
        }
    }
}

Ответы [ 4 ]

3 голосов
/ 02 июля 2019

Создание модели для поддержания состояния yesButton и noButton для каждого tableViewCell, т. Е.

class Model {
    var isYesSelected = false
    var isNoSelected = false
}

Создание пользовательского UITableViewCell с Outlets из yesButton и noButton.

Создайте один @IBAction для обоих buttons и обработайте их пользовательский интерфейс, в соответствии с которым набирается button.

Кроме того, используйте buttonTapHandler, чтобы определить row, в которомbutton постучал.Он будет вызываться каждый раз при нажатии button.Мы установим это при создании экземпляра TableViewCell в tableView(_:cellForRowAt:).

class TableViewCell: UITableViewCell {
    @IBOutlet weak var yesButton: UIButton!
    @IBOutlet weak var noButton: UIButton!

    var buttonTapHandler: (()->())?
    var model: Model?

    override func prepareForReuse() {
        super.prepareForReuse()
        yesButton.backgroundColor = .gray
        noButton.backgroundColor = .gray
    }

    func configure(with model: Model) {
        self.model = model
        self.updateUI()
    }

    @IBAction func onTapButton(_ sender: UIButton) {
        model?.isYesSelected = (sender == yesButton)
        model?.isNoSelected = !(sender == yesButton)
        self.updateUI()
    }

    func updateUI() {
        yesButton.backgroundColor = (model?.isYesSelected ?? false) ? .green : .gray
        noButton.backgroundColor = (model?.isNoSelected ?? false) ? .green : .gray
    }
}

UITableViewDataSource's tableView(_:cellForRowAt:) метод выглядит так:

let numberOfCells = 10
var models = [Model]()

override func viewDidLoad() {
    super.viewDidLoad()
    (0..<numberOfCells).forEach { _ in
        self.models.append(Model())
    }
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableViewCell
    cell.configure(with: models[indexPath.row])
    cell.buttonTapHandler = {
        print(indexPath.row)
    }
    return cell
}

Чтобы получитьtotalPoints, считать models с isYesSelected = true, то есть

let totalPoints = models.reduce(0) { (result, model) -> Int in
    if model.isYesSelected {
        return result + 1
    }
    return 0
}
print(totalPoints)
1 голос
/ 02 июля 2019
  • Создание базовой таблицы и настройка функций источника данных. image1

  • Создание ячейки tableView с двумя кнопками image2

  • Создание класса ячейки с кнопками розеток и действиями image3

  • Результат этого кода

result gif

Наслаждайтесь!

0 голосов
/ 02 июля 2019

Простой трехшаговый процесс ... !!

  1. Определить модель класса
  2. Подготовить таблицуПросмотреть ячейку и обработать действия
  3. Настройка tableView в контроллере представления

Начнем реализацию:

1) Определить класс модели

В пользовательском интерфейсе у нас есть такая информация, как вопрос и ответ (Да / Нет). Так что дизайн модели соответственно.

//MARK:- Class Declaration -
class Question {
      let questionText: String
      var answerState: Bool?

      init(question: String) {
           self.questionText = question
      }
}

2. Подготовить таблицуПросмотреть ячейку и обработать действия

Создание пользовательской ячейки tableView с Метка вопроса , Кнопка Да & Кнопка Нет . Свяжите это представление с уважаемыми @IBOutlets & @IBActions.

import UIKit

class TableViewCell: UITableViewCell {
      @IBOutlet weak var questionLabel: UILabel!
      @IBOutlet weak var yesButton: UIButton!
      @IBOutlet weak var noButton: UIButton!

      var question: Question?
      var toggle: Bool? {
          didSet {
                 question?.answerState = toggle
                 //Do buttons operations like...
                 if let isToggle = toggle {
                    yesButton.backgroundColor = isToggle ? .green : .gray
                    noButton.backgroundColor = isToggle ? .gray : .green
                 } else {
                    yesButton.backgroundColor =  .gray
                    noButton.backgroundColor = .gray
                 }
          }
      }

      func prepareView(forQuestion question: Question) {
           self.question = question
           questionLabel.text = question.questionText
           toggle = question.answerState
      }

      //Yes Button - IBAction Method
      @IBAction func yesButtonTapped(_ sender: UIButton) {
            toggle = true
      }

      //No Button - IBAction Method
      @IBAction func noButtonTapped(_ sender: UIButton) {
            toggle = false
      }
}

3. Настройка tableView в контроллере представления

class ViewController: UIViewController {

    //Prepare questions model array to design our tableView data source
    let arrQuestions: [Question] = [Question(question: "Do you speak English?"), Question(question: "Do you live in Chicago?")]
}

//MARK:- UITableView Data Source & Delegate Methods -
extension ViewController: UITableViewDataSource, UITableViewDelegate {

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as? TableViewCell else {
            return UITableViewCell()
        }
        tableViewCell.prepareView(forQuestion: arrQuestions[indexPath.row])
        return tableViewCell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80.0
    }
}
0 голосов
/ 02 июля 2019

Получите эту кнопку, используя ваш тег, как показано ниже, и после этого вы можете изменить значение по своему желанию.

var tmpButton = self.view.viewWithTag(tmpTag) as? UIButton
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...