swift - Firebase 删除后 UICollectionView 数据未删除

标签 swift firebase

我让我的用户按下单元格中的按钮,这会从 Firebase 后端删除数据。我希望同时移除单元格。它正在从 firebase 数据库中删除,但不会从 collectionView 中删除。如果我离开 View 并返回到 collectionView,那么它就会被删除。
在单击按钮后将其删除并且您留在 View 中时,如何才能发生这种情况?

 func didSelect(for cell: StaffSearchCell) {

    guard let indexpath = collectionView?.indexPath(for: cell) else { return }
    let studentUser = self.filteredUsers[indexpath.item]
    let selectedUserId = studentUser.uid
    guard let staffUID = Auth.auth().currentUser?.uid else { return }
    print("1st")

        // Add student to staff list
        let ref = Database.database().reference().child("staffUsers").child(staffUID).child("studentSession1List")
        let values = [selectedUserId: true]
        ref.updateChildValues(values) { (err, ref) in
            if let err = err {
                print("Failed to follow user:", err)
                return
            }

            print("student to staff")
        }

        // Add selected staff to student list
        let studentRef = Database.database().reference().child("studentUsers").child(selectedUserId).child("studentSession1List")
        studentRef.removeValue()
        let staffValues = [staffUID: true]
        studentRef.updateChildValues(staffValues) { (err, studentRef) in
            if let err = err {
                print("Failed to follow user:", err)
                return
            }
            print("staff to student")
        }

        let allStudentRef = Database.database().reference()
        allStudentRef.child("session1AllStudents").child(selectedUserId).removeValue() { (error, ref) in
            if error != nil {
                print("error \(error)")
            }
            print("removed from session1AllStudents")
            self.fetchRemainingStudents()
        }


    searchBar.isHidden = true
    searchBar.resignFirstResponder()

   // self.collectionView?.reloadData()
    //self.navigationController?.popViewController(animated: true)
}


var filteredUsers = [User]()
var users = [User]()

func fetchRemainingStudents() {
    print("second")
    let ref = Database.database().reference()
    ref.child("session1AllStudents").observeSingleEvent(of: .value, with: { (snapshot) in
        HUD.show(.labeledProgress(title: "Finding Students", subtitle: nil))
        for snap in snapshot.children {
            let studentsSnap = snap as! DataSnapshot
            let studentsKey = studentsSnap.key
            let studentDict = snapshot.value as! [String: Any]

            var aStudent = User(uid: studentsKey, dictionary: studentDict)
            let userRef = ref.child("studentUsers").child(studentsKey)
            userRef.observeSingleEvent(of: .value, with: { snapshot in
                let userDict = snapshot.value as! [String:AnyObject]
                let firstName = userDict["firstName"] as! String
                let lastName = userDict["lastName"] as! String
                let email = userDict["email"] as! String

                aStudent.firstName = firstName
                aStudent.lastName = lastName
                aStudent.email = email
                self.users.append(aStudent)

                self.filteredUsers = self.users
                //                    self.users.sort(by: { (u1, u2) -> Bool in
                //
                //                        return u1.lastName.compare(u2.lastName) == .orderedAscending
                //                    })
                HUD.hide()
                self.collectionView?.reloadData()
            })

        }

    })


}

单元格:

protocol StaffSearchCellDelegate {

func didSelect(for cell: StaffSearchCell)}

类 StaffSearchCell:UICollectionViewCell {

var delegate: StaffSearchCellDelegate?


var user: User? {
    didSet {

        lastNameLabel.text = user?.lastName
        firstNameLabel.text = user?.firstName

        guard let email = user?.email else { return }

        if email == "" {
            emailLabel.text = ""
        } else {
            emailLabel.text = user?.email

        }

    }
}


let firstNameLabel: UILabel = {
    let label = UILabel()
    label.text = "First Name"
    label.font = UIFont.boldSystemFont(ofSize: 12)
    return label
}()

let lastNameLabel: UILabel = {
    let label = UILabel()
    label.text = "Last Name"
    label.font = UIFont.boldSystemFont(ofSize: 12)
    return label
}()

let emailLabel: UILabel = {
    let label = UILabel()
    label.text = "@email"
    label.font = UIFont.systemFont(ofSize: 11)
    label.textColor = UIColor.lightGray
    label.textAlignment = .left
    return label
}()


lazy var addSessionButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Add", for: .normal)
    button.addTarget(self, action: #selector(handleSelectSession), for: .touchUpInside)
    button.backgroundColor = UIColor.bulldogGold().withAlphaComponent(0.75)
    button.setTitleColor(UIColor.black, for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
    button.layer.cornerRadius = 5
    return button
}()

func handleSelectSession() {
    print("student selected")
    delegate?.didSelect(for: self)
}


override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(firstNameLabel)
    addSubview(lastNameLabel)
    addSubview(emailLabel)
    addSubview(addSessionButton)

    firstNameLabel.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: lastNameLabel.leftAnchor, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)

    lastNameLabel.anchor(top: topAnchor, left: firstNameLabel.rightAnchor, bottom: bottomAnchor, right: emailLabel.leftAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 0, height: 0)

    emailLabel.anchor(top: topAnchor, left: lastNameLabel.rightAnchor, bottom: bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 8, width: 0, height: 0)

    addSessionButton.anchor(top: topAnchor, left: nil, bottom: bottomAnchor, right: rightAnchor, paddingTop: 4, paddingLeft: 4, paddingBottom: 4
        , paddingRight: 4, width: 50, height: 0)


    let separatorView = UIView()
    separatorView.backgroundColor = UIColor(white: 0, alpha: 0.5)
    addSubview(separatorView)
    separatorView.anchor(top: nil, left: firstNameLabel.leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0.5)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}}

最佳答案

我需要对数据数组执行removeAll,然后使用我的获取函数重新加载用户。

关于swift - Firebase 删除后 UICollectionView 数据未删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46995802/

相关文章:

ios - 无法将 Int 类型的值分配给 Swift 2.1 中 Int 数组的元素

Swift enum 使用 String 值获取 Int Enum 的值

IOS查看容器: how to set the delegate

android - 在 firebase 数据库中保存数据后如何进入下一个 Activity

ios - Swift - 延迟状态栏图标加载

ios - ScrollView 内容未填充 SwiftUI

image - flutter 和 Firebase : How to check if my picture is uploaded to Firebase Storage Successfully?

python - Flutter web 中的 HTTP 触发 Cloud Function

Firebase:在 URL 重写中传递 url 参数

firebase - 异步函数中的异步操作