Обновление UITableView's numberOfRowsInSection после асинхронного вызова - PullRequest
0 голосов
/ 26 августа 2018

У меня есть UITableView, который должен отображать сообщения, которые загружаются (асинхронно) из базы данных.Там может быть никаких сообщений, поэтому я хотел бы отображать статический текст, говорящий об этом явно.Проблема в том, что после загрузки данных и их кэширования в массив, UILabel, помещенный в tableView.backgroundView, все еще там.Я не уверен почему.Вот мой код:

@IBOutlet weak var tableView: UITableView!    
var messages = [Message]()
var users = [UserModel]()

override func viewDidLoad() {
    super.viewDidLoad()
    loadMessages()
}

 // All of these are called Async
 func loadMessages() {
    guard let userUid = Api.Users.CURRENT_USER?.uid else { return }
    Api.Message.observeUsersMessagesForUser(withId: userUid) { messageKey in
        Api.Message.observeMessage(with: messageKey, completion: { message in
            self.fetchUsers(userId: message.to!, completion: {
                self.messages.append(message)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            })
        })
    }
}

func fetchUsers(userId: String, completion: @escaping () -> Void) {
    Api.Users.observeUsersShort { user in
        self.users.append(user)
        completion()
    }
}

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if messages.isEmpty {
        showNoDataTableView()
        return 0
    }
    else {
        return messages.count
    }
}

 func showNoDataTableView() {
  //  self.activityIndicator.stopAnimating()
    if messages.isEmpty {
        let noDataLabel: UILabel  = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width,
                                                          height: self.tableView.bounds.size.height))
        noDataLabel.numberOfLines = 0
        noDataLabel.text = "No messages yet :( \r\n\n Don't be afraid to start a conversation."
        noDataLabel.textColor = Theme.current.label_noData_textColor
        noDataLabel.font = Theme.current.label_noData_font
        noDataLabel.textAlignment = .center
        tableView.backgroundView  = noDataLabel
        tableView.backgroundView?.backgroundColor = Theme.current.tableView_backgroundView_backgroundColor
        tableView.separatorStyle  = .none
    }
}

1 Ответ

0 голосов
/ 26 августа 2018

Прежде всего, не ставьте showNoDataTableView() в numberOfRowsInSection. Просто верните обычный

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

и укажите showNoDataTableView() в асинхронном закрытии отправки в loadMessages()

DispatchQueue.main.async {
    self.tableView.reloadData()
    showNoDataTableView()
}

В showNoDataTableView() вы должны проверить

  • Создайте метку, если messages пуст, а метка не существует (пока).
  • Удалите метку, если messages равен , а не пуст и метка существует .

В обоих остальных случаях ничего не делать.

 func showNoDataTableView() {
  //  self.activityIndicator.stopAnimating()
    if messages.isEmpty && tableView.backgroundView == nil {
        let noDataLabel: UILabel  = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width,
                                                          height: self.tableView.bounds.size.height))
        noDataLabel.numberOfLines = 0
        noDataLabel.text = "No messages yet :( \r\n\n Don't be afraid to start a conversation."
        noDataLabel.textColor = Theme.current.label_noData_textColor
        noDataLabel.font = Theme.current.label_noData_font
        noDataLabel.textAlignment = .center
        tableView.backgroundView  = noDataLabel
        tableView.backgroundView?.backgroundColor = Theme.current.tableView_backgroundView_backgroundColor
        tableView.separatorStyle  = .none
    } else if !messages.isEmpty && tableView.backgroundView != nil {
        tableView.backgroundView  = nil
        tableView.separatorStyle  =  // set default style
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...