перезагрузить строки без вызова tableview.reload - PullRequest
0 голосов
/ 16 октября 2018

Здравствуйте, в моем приложении я добавляю данные в массив, затем вставляю строки в табличное представление следующим образом:

 self.table.beginUpdates()
 self.datasource.append(Data)
 self.table.insertRows(at: [IndexPath(row: self.datasource.count-1, section: 0)], with: .automatic)
 self.table.endUpdates()

в этом коде все работает нормально, теперь, когда я хочу провести пальцем, чтобы обновить все строкино я не хочу использовать table.reloadData, потому что он удаляет все записи и показывает белый экран в течение нескольких секунд, я хочу перезагрузить все строки, не используя его, я пытаюсь таким образом, но это приводит к сбою приложения

@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
        if (datasource.count > 0 ){
            datasource.removeAll() 
             page_num = 1
            get_past_orders(page: page_num)
              self.isLoading =  false
            refreshControl.endRefreshing()
        }
    }

сбой приложения при

   self.table.endUpdates()
Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)

Ответы [ 3 ]

0 голосов
/ 16 октября 2018

Если вы хотите перезагрузить строку tableView без вызова метода перезагрузки tableView каждый раз.Вы можете использовать

self.itemTableView.reloadRows(at: [NSIndexPath(row: 0, section: 0) as IndexPath], with: .automatic)

Вы можете вставить желаемое значение IndexPath (вы хотите перезагрузить) в месте

[NSIndexPath(row: 0, section: 0) as IndexPath]

и с: здесь есть тип типа UITableViewRowAnimation, который вы хотитеперезагрузить с анимацией.Он предоставляет множество опций, таких как .automatic, .bottom, .fade, .middle, .top, .left, .right и .none и т. Д.

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

0 голосов
/ 16 октября 2018

Использование Objective-C:

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];
0 голосов
/ 16 октября 2018

Ваш подход был верным:

Вы также должны добавить новый элемент в свой "список предметов"

items.append(newItem)

let selectedIndexPath = IndexPath(row: items.count - 1, section: 0)

tableView.beginUpdates()
tableView.insertRows(at: [selectedIndexPath], with: .automatic)
tableView.endUpdates()

вот и все:)


РЕДАКТИРОВАТЬ: Пример

небольшой пример, который идеально подходит для меня:

class ViewController: UIViewController {

    struct Item {
        var field_a: String
        var field_b: Bool
        var field_c: Int
    }

    // MARK: - properties
    var items = [Item]()

    // MARK: - object-properties
    let tableView = UITableView()
    let addButton = UIButton()

    // MARK: - system-methods
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(tableView)
        tableView.addSubview(addButton)

        addButton.titleLabel?.text  = "ADD"
        addButton.titleLabel?.textColor = .white
        addButton.backgroundColor   = .blue
        addButton.addTarget(self, action: #selector(handleButton), for: .touchUpInside)

        tableView.dataSource  = self

        addButton.anchor(top: nil, leading: nil, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 24), size: CGSize(width: 84, height: 48))
        tableView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor)

        prepareItems()
    }

    // MARK: - preparation-methods

    func prepareItems() {
        items.append(Item(field_a: "cell1", field_b: false, field_c: 0))
        items.append(Item(field_a: "cell2", field_b: false, field_c: 0))
        items.append(Item(field_a: "cell3", field_b: false, field_c: 0))

    }

    // MARK: - helper-methods

    func appendNewItem(_ item: Item) {
        items.append(item)

        let selectedIndexPath = IndexPath(row: items.count - 1, section: 0)

        tableView.beginUpdates()
        tableView.insertRows(at: [selectedIndexPath], with: .automatic)
        tableView.endUpdates()
    }

    // MARK: - action-methods

    @objc func handleButton() {
        appendNewItem(Item(field_a: "new Cell", field_b: true, field_c: 0))
    }
}

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let currItem = items[indexPath.row]

        cell.textLabel?.text    = currItem.field_a

        return cell
    }
}

fyi: .anchor () - метод, написанный мной.- устанавливает все ограничения AutoLayout.

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