Как отметить ячейки табличного представления в данных ячейки swift4, поступающих с сервера - PullRequest
0 голосов
/ 05 июля 2019

Как я пытался в некоторых сценариях, но не работал идеально, если я выбрал вторую ячейку, флажок в первой ячейке не отмечен, а иногда функциональность вообще не работает, пока я не нажму 10-20 раз. Вот мой код.

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

    if tableView == switchTableView{
       return self.arrdata20.count
    } else
    {
        return self.arrdata.count
    }

    }


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

    if (tableView == self.switchTableView)
    {

        let cell:switchTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! switchTableViewCell

        cell.nameLbl.text = (arrdata20[indexPath.row].name)
        print(cell.nameLbl.text)
        if (arrdata20[indexPath.row].emp_id == "001")
        {
            cell.isHidden=true
        }
        else{
            cell.isHidden=false
        }
        return cell



    }
    else  {
        let cell:PartyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PartyTableViewCell
        cell.venuLbl.text = "Venu: \(arrdata[indexPath.row].place)"
        cell.dateTimeLbl.text = "Date & Time: \(arrdata[indexPath.row].date)"
        cell.reasonLbl.text = "Reason: \(arrdata[indexPath.row].reason)"
        //        cell.timeLbl.text = ""
        return cell
    }

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    var rowHeight:CGFloat = 0.0
    if tableView == self.switchTableView{
    if(arrdata20[indexPath.row].emp_id == "001")
    {
        rowHeight = 0.0
    }
    else
    {
        rowHeight = UITableViewAutomaticDimension  
    }

    return rowHeight
    }else{
        return UITableViewAutomaticDimension
    }

}

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


    id1 = "\(arrdata[indexPath.row].id)"
    print(id1)

        if self.switchTableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark
        {
           self.switchTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none

        }
        else{
            self.switchTableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark



    }
}

После выбора ячеек tableView мне нужно получить детали ячеек галочки, такие как имена в ячейке, как показано на рисунке ниже enter image description here

Ответы [ 2 ]

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

Вы должны обновить свой

tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) метод как

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! switchTableViewCell
        if cell.accessoryType == .checkmark {
            cell.accessoryType = .none
        } else {
            cell.accessoryType = .checkmark
        }
}

Но если вы хотите, чтобы ячейка сохраняла свой accessoryType даже после перезагрузки, вам нужно создать массив для отслеживания вашего accessoryType для каждой ячейки и обновить его значение в массиве при обновлении accessoryType в пользовательском интерфейсе в didSelectRowAt () и затем в cellForRowAt () вы должны использовать этот массив для установки accessoryType для каждой ячейки.

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

Вы должны объявить массив как:

var checked = [Bool]()

Затем добавьте эту строку кода в вызов API, где вы получите данные в массиве

self.checked = Array(repeating: false, count: self.arraydata.count)

В методе делегата табличного представления:

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

    let cell:switchTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! switchTableViewCell

    //configure you cell here.
    if checked[indexPath.row] == false{
        cell.accessoryType = .none


    } else if checked[indexPath.row] {
        cell.accessoryType = .checkmark


    }
    cell.title.text = self. arraydata[indexPath.row]["amp_id"].string
    return cell

}

добавьте еще один метод делегата:

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

    tableView.deselectRow(at: indexPath, animated: true)
    if let cell = tableView.cellForRow(at: indexPath as IndexPath) {

        if cell.accessoryType == .checkmark {
            cell.accessoryType = .none
            checked[indexPath.row] = false


        } else  {
            cell.accessoryType = .checkmark
            checked[indexPath.row] = true


        }
    }

    on OKClickedButtonAction:

    serviceString = ""
    for i in 0..<checked.count{
        if checked[i] == true{
            serviceString = serviceString + self.arraydata[i]["emp_id"].string! + ", "
            print(serviceString)

        }
    }
    if serviceString == ""{
        self.servicesBtnLbl.text = "Tap to select"
    }else{
        self.servicesBtnLbl.text = serviceString

    }

Это работает Решение, надеюсь, оно будет вам полезно.

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