Как выполнить данные внутри TableViewCell в виде кнопки? - PullRequest
2 голосов
/ 27 марта 2019

enter image description here Я создаю приложение, в котором меню перечислены внутри TableViewCell. Меню уже находятся внутри ячейки, но, к сожалению, когда я щелкнул по одному из меню, оно не выполняет действие, которое должно выполнить меню. Например, я нажал logout label, который не выполняется showlogoutDialog. Я уже использовал точки останова, но кажется, что данные внутри таблицы - просто текст. Изображение ниже - пример выходных данных таблицы. Надеюсь, вы можете дать какое-то решение по этому вопросу. Спасибо.

Screen Record

DoctorMenuTableCell.swift

class DoctorMenuTableCellTableViewCell: UITableViewCell {


@IBOutlet weak var titleLabel: UILabel!


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
}

MoreOptionViewController.swift

private let menuIdentifier = "MenuCell"

class MoreOptionViewController: UIViewController {

@IBOutlet weak var doctorMenuTableView: UITableView!

}

override func viewDidLoad() {
    super.viewDidLoad()

self.doctorMenuTableView.dataSource = self
self.doctorMenuTableView.delegate = self

}

//MARK: Function

func showLogoutDialog() {
    //create alert
    let alert = UIAlertController(title: "Confirmation",  message: "Are you sure you want to logout?", preferredStyle: .alert)

    //add the actions (button)
    alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
    alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert) in
        self.logout()
    }))
    self.present(alert, animated: true, completion: nil)

}

func logout() {
    NotificationCenter.default.post(name: Notification.Name(deleteUserDataNotificationName), object: nil)
   }

}


extension MoreOptionViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {  
  case 0:
      return Menu.More.items.count
  default: return 0
 }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = indexPath.row

    switch indexPath.section {
    case 0:
        let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell

        cell.titleLabel.text = Menu.More.items[row].value

        if row == 1{
            cell.titleLabel.textColor = UIColor.red
            cell.accessoryType = .none   
        }

        return cell
    default:
        return UITableViewCell()
    }
}

func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.section {
    case 0: break
    case 1:
        switch indexPath.row {
            case 0:
                let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default))

                self.present(alertController, animated: true, completion: nil)
        case 1: showLogoutDialog()
        default: break
    }

    default: break

    }

}

Ответы [ 3 ]

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

Проверьте ваш Did Select метод, ваши cells ниже Section 0 и Did Select работают для section 1.

Также проверьте isUserInteractionEnabled как для TableView, так и для Cell, добавьте точку останова на didSelectRowAt и проверьте, какой корпус переключателя работает.

Код:

func numberOfSections(in tableView: UITableView) -> Int {
  return 2
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   switch section {  
     case 0:
         return Menu.More.items.count
     default: return 0
    }
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.section {
      case 0:
          let cell = tableView.dequeueReusableCell(withIdentifier: menuIdentifier, for: indexPath) as! DoctorMenuTableCell
          cell.titleLabel.text = Menu.More.items[row].value

          if indexPath.row == 1{
              cell.titleLabel.textColor = UIColor.red
              cell.accessoryType = .none   
          }

         return cell
      default:
         return UITableViewCell()
      }
 }



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   switch indexPath.section {
    case 1: break
    case 0:
         switch indexPath.row {
           case 0:
              let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
              alertController.addAction(UIAlertAction(title: "OK", style: .default))

              self.present(alertController, animated: true, completion: nil) 
            break
            case 1: showLogoutDialog()
            break
            default: break
         }
         break
         default: break

     }

  }
0 голосов
/ 27 марта 2019

Сначала создайте расширение, если UIViewController как ниже,

Создайте быстрый файл с именем Extension.swift или как хотите,

extension UIViewController
{
    func showLogoutDialog() {
        //create alert
        let alert = UIAlertController(title: "Confirmation",  message: "Are you sure you want to logout?", preferredStyle: .alert)

        //add the actions (button)
        alert.addAction(UIAlertAction(title: "No", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert) in
            self.logout()
        }))
        self.present(alert, animated: true, completion: nil)

    }
    func logout() {
        print("helllllo")
        NotificationCenter.default.post(name: Notification.Name(deleteUserDataNotificationName), object: nil)
    }
}

Теперь вызовите showLogoutDialog () для cellForRowAt,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   switch indexPath.section {
    case 1: break
    case 0:
         switch indexPath.row {
           case 0:
              let alertController = UIAlertController(title: "Info", message: "your data", preferredStyle: .alert)
              alertController.addAction(UIAlertAction(title: "OK", style: .default))

              self.present(alertController, animated: true, completion: nil) 
            break
            case 1: showLogoutDialog()
            break
            default: break
         }
         break
         default: break

     }
0 голосов
/ 27 марта 2019

Посмотрите, сколько у вас разделов. У вас есть только один, но внутри didSelectRowAt вы показываете предупреждения, только если индекс раздела равен 1, а в вашем случае индекс никогда не будет.

Вам просто нужно проверить, равна ли строка 0 или 1

func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {
    case 0: 
        let alertController = UIAlertController(title: "Info", message: "No available data", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .default))
        present(alertController, animated: true)
    case 1:
        showLogoutDialog()
    default: 
        return
    }
}

Итак, если у вас есть только один раздел, вы также можете обновить методы источника данных. Также вы должны обрабатывать случаи, когда ячейка не находится в IndexPath с индексом строки 1, так как ячейки сняты с очереди

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

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

    let row = indexPath.row
    cell.titleLabel.text = Menu.More.items[row].value

    cell.titleLabel.textColor = .black 
    cell.accessoryType = .detailButton

    if row == 1
        cell.titleLabel.textColor = .red
        cell.accessoryType = .none
    }

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