Выберите один выбор из ячейки в Swift - PullRequest
0 голосов
/ 20 мая 2018

у меня есть табличное представление, в котором есть два раздела и ячейки под ним.Пользователь может выбрать только одну ячейку из каждого раздела, я попробовал некоторый код для выбора, когда я выбираю любую ячейку из раздела 0, он удаляет отметку из раздела 1, а когда я выбираю любую ячейку из раздела 1, он удаляет знак отметки из раздела0, и я также хочу, чтобы когда табличное представление загружало свою первую ячейку каждого раздела, должен быть предварительно выбран.у меня есть код для одиночного выбора в моем табличном представлении, но для предварительного выбора у меня нет идеи, так как я могу предварительно выбрать ячейку. Это мой код,

extension FiltersVC: UITableViewDelegate,UITableViewDataSource{

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

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sectionTitles[section]
}

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

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 60
}

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

    cell.tilteLbl.text = menuItems[indexPath.section][indexPath.row]
    cell.selectionStyle = UITableViewCellSelectionStyle.none
    cell.accessoryType = cell.isSelected ? .checkmark : .none
    cell.selectionStyle = .none
    cell.backgroundColor = UIColor.clear
    return cell
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 30
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UIView()
    headerView.backgroundColor = #colorLiteral(red: 0.9130856497, green: 0.9221261017, blue: 0.9221261017, alpha: 1)

    let headerText = UILabel()
    headerText.textColor = UIColor.black
    headerText.adjustsFontSizeToFitWidth = true
    switch section{
    case 0:
        headerText.textAlignment = .center
        headerText.text = "LIST BY"
        headerText.backgroundColor = #colorLiteral(red: 0.9190355449, green: 0.9281349067, blue: 0.9281349067, alpha: 1)
        headerText.font = UIFont.boldSystemFont(ofSize: 20)
    case 1:
        headerText.textAlignment = .center
        headerText.text = "COUSINE"
        headerText.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
        headerText.font = UIFont.boldSystemFont(ofSize: 20)
    default: break

    }

    return headerText

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.section == 0 {
        if let cell = filterTableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark

            let item = menuItems[indexPath.section][indexPath.row]
            UserDefaults.standard.set(item, forKey: "listBy")
            UserDefaults.standard.synchronize()
            filterBtn.isUserInteractionEnabled = true
            filterBtn.backgroundColor = #colorLiteral(red: 0.9529120326, green: 0.3879342079, blue: 0.09117665142, alpha: 1)
        }
    }
    else {
        if let cell = filterTableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark

            let item = menuItems[indexPath.section][indexPath.row]
            UserDefaults.standard.set(item, forKey: "Cuisine")
            UserDefaults.standard.synchronize()
            filterBtn.isUserInteractionEnabled = true
            filterBtn.backgroundColor = #colorLiteral(red: 0.9529120326, green: 0.3879342079, blue: 0.09117665142, alpha: 1)
        }
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if indexPath.section == 0 {
        if let cell = filterTableView.cellForRow(at: indexPath as IndexPath) {
            cell.accessoryType = .none
        }
    }
    else{
        if let cell = filterTableView.cellForRow(at: indexPath as IndexPath) {
            cell.accessoryType = .none
        }
    }
}

1 Ответ

0 голосов
/ 20 мая 2018

Вам необходимо включить множественный выбор.В viewDidLoad() введите:

tableView.allowsMultipleSelection = true

Затем обработайте только один выбор в каждом разделе в методе делегата didSelectRow(), отметив tableView.indexPathsForSelectedRows, который возвращает массив путей индекса.

Например:

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

    // Get list of all selected index paths (includes one just selected, so may be up to 3)
    var selectedIndexPaths = tableView.indexPathsForSelectedRows!

    // Remove index path that was just selected
    if selectedIndexPaths.contains(indexPath) {
        selectedIndexPaths.remove(at: selectedIndexPaths.index(of: indexPath)!)
    }

    if indexPath.section == 0 {

        // Get any selected index paths in section 0
        let selectionInSection0 = selectedIndexPaths.filter { $0.section == 0 }
        if !selectionInSection0.isEmpty {
            // Deselect the preciously selected row in section 0
            tableView.deselectRow(at: selectionInSection0.first!, animated: true)
        }

        // Other required code from user
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark
            let item = menuItems[indexPath.section][indexPath.row]
            UserDefaults.standard.set(item, forKey: "listBy")
            UserDefaults.standard.synchronize()
            filterBtn.isUserInteractionEnabled = true
            filterBtn.backgroundColor = #colorLiteral(red: 0.9529120326, green: 0.3879342079, blue: 0.09117665142, alpha: 1)
        }

    } else if indexPath.section == 1 {

        // Get any selected index paths in section 1
        let selectionInSection1 = selectedIndexPaths.filter { $0.section == 1 }
        if !selectionInSection1.isEmpty {
            // Deselect the preciously selected row in section 1
            tableView.deselectRow(at: selectionInSection1.first!, animated: true)
        }

        // Other required code from user
        if let cell = tableView.cellForRow(at: indexPath) {
            cell.accessoryType = .checkmark
            let item = menuItems[indexPath.section][indexPath.row]
            UserDefaults.standard.set(item, forKey: "Cuisine")
            UserDefaults.standard.synchronize()
            filterBtn.isUserInteractionEnabled = true
            filterBtn.backgroundColor = #colorLiteral(red: 0.9529120326, green: 0.3879342079, blue: 0.09117665142, alpha: 1)
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...