Получение индекса TableViewCell равно нулю при выборе выпадающего элемента - PullRequest
0 голосов
/ 26 февраля 2019

Я хочу индекс ячейки таблицы при выборе выпадающего списка.Но индекс ноль, когда я нажимаю на выпадающий элемент.Есть ли способ получить индекс при выборе выпадающего элемента?Если у кого-нибудь есть лучшее решение, дайте мне некоторое представление.

let EditDropDown = DropDown()
lazy var dropDowns: [DropDown] = {
    return [
        self.EditDropDown
    ]
}()

Это моя функция, которую я использую для DropDown List.

func setupGenderDropDown() {

        let cellHeader = tableview.dequeueReusableCell(withIdentifier: "CellRIDHeader") as! SPOccupationCell

        EditDropDown.anchorView = cellHeader.btnDots
        EditDropDown.bottomOffset = CGPoint(x: 0, y: 40)

        // You can also use localizationKeysDataSource instead. Check the docs.
        EditDropDown.dataSource = [
            "Edit",
            "Make Default",
            "Delete"
        ]

        // Action triggered on selection
        EditDropDown.selectionAction = { [weak self] (index, item) in
            cellHeader.btnDots.setTitle(item, for: .normal)

            if item == "Edit"
            {
                // I am Getting Cell Index but index is nil
                let cell = self!.tableview.dequeueReusableCell(withIdentifier: "CellRIDHeader") as! SPOccupationCell

                let indexPath = self!.tableview.indexPath(for: cell)
                    print(indexPath as Any)

                let occupation_id = self!.arrayOccupation[(indexPath?.row)!].occupation_Main_id
                    print(occupation_id)

                    let next = self!.storyboard?.instantiateViewController(withIdentifier: "EditOccupationVCSID") as! EditOccupationVC
                self!.navigationController?.pushViewController(next, animated: false)
                    next.occupationId = occupation_id



            }
            else if item == "Make Default"
            {
                print("B")
            }
            else if item == "Delete"
            {
                print("c")
            }
        }
    }

1 Ответ

0 голосов
/ 26 февраля 2019

Я предполагаю, что вы используете библиотеку DropDown для отображения выпадающего списка.Существует проблема, когда вы получаете ячейку при ее нажатии, поэтому я создал для вас демонстрационный проект (простой tableView, а не с пользовательским UITableViewCell), и я добавил комментарий, чтобы объяснить изменения.Рассмотрим код ниже:

import UIKit
import DropDown

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var items: [String] = ["We", "Heart", "Swift"]

    let editDropDown = DropDown() //Object name should start with small letter

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    func setupGenderDropDown(cell: UITableViewCell) { //Pass your cell with argument and change type to your custom cell

        //By changing cell argument with your custom cell you will get your button for anchor
        editDropDown.anchorView = cell.textLabel
        editDropDown.bottomOffset = CGPoint(x: 0, y: 40)

        editDropDown.dataSource = [
            "Edit",
            "Make Default",
            "Delete"
        ]

        //Here you need to update selectionAction from their library page
        editDropDown.selectionAction = { [unowned self] (index: Int, item: String) in

            //Here you will get selected item and index
            print("Selected item: \(item) at index: \(index)")
            if item == "Edit"
            {
                print(item)
                print(index)
            }
            else if item == "Make Default"
            {
                print("B")
            }
            else if item == "Delete"
            {
                print("c")
            }
        }

        //This was missing in your code
        editDropDown.show()
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

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

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //Get the selected cell this way
        guard let indexPath = tableView.indexPathForSelectedRow else { return }
        guard let currentCell = tableView.cellForRow(at: indexPath) else { return }

        //Pass your selected cell to setupGenderDropDown method
        setupGenderDropDown(cell: currentCell)
    }
}

ЗДЕСЬ вы можете проверить демонстрационный проект.И это создано в Xcode 10.1

...