CellForRow не вызывается при переключении между приложениями (gif внутри) - PullRequest
3 голосов
/ 24 января 2020

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = chatUser.dequeueReusableCell(withIdentifier: "chatUserCell", for: indexPath) as! ChatUserTableViewCell
    print("cellforrowcalled")
    cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))

    // I check here the message sender
    cell.isFromCurrentUser = messages[indexPath.row].fromUid == UserApi.shared.CURRENT_USER_UID!

    cell.labelChatMessage.text = messages[indexPath.row].chatText

    cell.labelChatMessageDate.text = messages[indexPath.row].chatDate?.dateValue().timeAgo(numericDates: false)

    return cell
}

В моем ChatCellViewController я изменяю ограничения в соответствии с логическим значением "isFromCurrentUser":

var isFromCurrentUser: Bool! {
    didSet {
        labelChatMessage.backgroundColor = isFromCurrentUser ? .systemBlue : .darkGray

        if isFromCurrentUser {
            constraintOtherUserTimestamp.isActive = false
            constraintOtherUserLeading.isActive = false
            constraintOtherUserTrailing.isActive = false
            constraintCurrentUserTimestamp.isActive = true
            constraintCurrentUserLeading.isActive = true
            constraintCurrentUserTrailing.isActive = true
        } else {
            constraintCurrentUserTimestamp.isActive = false
            constraintCurrentUserLeading.isActive = false
            constraintCurrentUserTrailing.isActive = false
            constraintOtherUserTimestamp.isActive = true
            constraintOtherUserLeading.isActive = true
            constraintOtherUserTrailing.isActive = true
        }
    }
}

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

enter image description here

Ответы [ 2 ]

4 голосов
/ 24 января 2020

Вы должны прослушать уведомление для приложения, входящего на передний план, например: UIApplication.willEnterForegroundNotification

В вашем viewDidLoad() добавьте наблюдателя:

NotificationCenter.default.addObserver(self, selector: #selector(resumeState), name: UIApplication.willEnterForegroundNotification, object: nil)

, затем объявите функцию resumeState() , это будет вызвано, когда приложение переходит в состояние переднего плана.

@objc func resumeState() {
    yourTableView.reloadData()
}

Также не забудьте удалить наблюдателя в deinit

deinit {
    print("\(self.description) deinitialized")
    NotificationCenter.default.removeObserver(self)
}
0 голосов
/ 24 января 2020

Вы можете вызвать tableView.delegate = self & tableView.dataSource = self on ViewWillAppear

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