Как добавить новые ячейки и новые заголовки без перезагрузки таблицы в Swift 4? - PullRequest
0 голосов
/ 31 августа 2018

Я видел много ответов на мой запрос, но мой ответ не помог. Я открываю новый вопрос здесь.

У меня есть API, который возвращает данные. Я показываю это в шапке и ячейке. И есть кнопка загрузки еще, если API возвращает 1 for has_more key. Поэтому, когда я нажимаю на кнопку «загрузить еще», я снова вызываю этот API, чтобы получить оставшиеся данные, но он также обновляет все табличное представление, поскольку я перезагружаю табличное представление.

Итак, теперь я хочу добавить новые ячейки и заголовки без перезагрузки существующего табличного представления, чтобы не затрагивать предыдущие заголовки и ячейку в табличном представлении.

Это функция API:

func getOverallWinners(has: Int)
{
    let params = ["api_token": Constants.USER_INFO["api_token"].rawValue,"has_more": has]

    ServiceHelper.sharedInstance.sendRequest(path: "contest-overall-winning", params: params, showSpinner: true)
    { (response, error) in

        if error != nil
        {
            print("Error: \(error.debugDescription)")
        }
        else
        {
            self.winnerArr     = response["result"].arrayObject as? Array<Dictionary<String,Any>>

            self.overallL.text = "$\(String(describing: response["overall"].rawString()!))"

            self.winningTbl.beginUpdates()

            let indexPath:IndexPath = IndexPath(row:((self.winnerArr?.count)! - 1), section:0)

            self.winningTbl.insertRows(at: [indexPath], with: .left)

            self.winningTbl.endUpdates()

            self.winningTbl.scrollToRow(at: indexPath, at: .bottom, animated: true)

            let loadMore = response["has_more"].rawValue as? Int

            if  loadMore == 0
            {
                self.constantHeight4LoadMore.constant = 0

            }
            else
            {
                self.constantHeight4LoadMore.constant = 40
            }

        }
    }
}

Вот делегат tableView:

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

    return (winnerArr?.count)!
}

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

    let rowArray =  winnerArr![section]["response"] as? Array<Dictionary<String,Any>>

    return rowArray!.count

}


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

    return 60
}

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

    return 60
}


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

    let header =  tableView.dequeueReusableHeaderFooterView(withIdentifier: cellReuseIdentifier) as! OverallHeaderCell

    let resArr   = self.winnerArr![section]["response"]! as? Array<Dictionary<String,Any>>

    for prize in resArr!
    {
        let doubleStr = prize["prize"] as? NSString

        self.prizeArr.append((doubleStr?.doubleValue)!)
    }

    let sumedStr = prizeArr.reduce(0, +)

    header.textL[0].text = winnerArr![section]["name"] as? String

    header.textL[1].text = "$\(sumedStr)"

    header.textL[3].text = "\(String(describing: resArr!.count))"

    return header
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: "owCell", for: indexPath) as! OWCell

    let response = winnerArr![indexPath.section]["response"] as? Array<Dictionary<String,Any>>

    cell.collectionL[0].text = (response![indexPath.row]["name"] as! String)

    cell.collectionL[1].text = "$\(String(describing:response![indexPath.row]["prize"]!))"

    cell.collectionL[2].text = "WIN"

    cell.selectionStyle        = .none

    return cell
}

Я пробовал beginUpdates() выше, но ничего не получалось, так как каждый раз, когда я нажимаю кнопку «Загрузить больше», я получаю новые заголовки. В этих заголовках будут новые ячейки. Кто-нибудь может помочь?

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

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