swift 排序单元格而不是表格

0sgqnhkj  于 2022-12-26  发布在  Swift
关注(0)|答案(1)|浏览(142)

我的应用会检查用户关注的是哪个兴趣点/订阅源/群组。在此基础上,它会加载评论内容和用户名/图片。这些内容是单独加载的。我唯一的问题是按时间排序。
如果我使用这个代码:评论的排序是正确的。但是个人资料名称和图片的匹配是完全错误的。
如果我删除上面的代码,匹配是正确的,但排序是完全错误的。我该如何解决这个问题?而不是排序表,我必须排序单元格本身?

func loadFollowedPoi() {
    myFeed.myArray1 = []
    let userID = Auth.auth().currentUser!.uid
    let database = Database.database().reference()
    database.child("user/\(userID)/abonniertePoi/").observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children.allObjects as! [DataSnapshot] {
            myFeed.myArray1.append(child.key)
        }
        self.postsLaden()
    })
}

func postsLaden() {
    dic = [:]
    
    let neueArray: [String] = []
    for groupId in myFeed.myArray1[0..<myFeed.myArray1.count] {
        
        let placeIdFromSearch = ViewController.placeidUebertragen
        ref = Database.database().reference().child("placeID/\(groupId)")
        ref.observe(DataEventType.childAdded, with: { snapshot in
            
            guard let dic = snapshot.value as? [String: Any] else { return }
            let newPost = importPosts(dictionary: dic, key: snapshot.key)
            guard let userUid = newPost.userID else { return }

            self.fetchUser(uid: userUid, completed: {
                self.table.insert(newPost, at: 0)
                self.table = self.table.sorted(by: { $0.userTime ?? 0 > $1.userTime ?? 0 })

                self.tableView.reloadData()
            })
        }
        )}
    
}

func fetchUser(uid: String, completed: @escaping () -> Void) {
    ref = Database.database().reference().child("user").child(uid).child("userInformation")
    ref.observe(.value) { (snapshot) in
        guard let dic = snapshot.value as? [String: Any] else { return }
        let newUser = UserModel(dictionary: dic)
        self.users.insert(newUser, at: 0)
        completed()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        cell.layoutMargins = UIEdgeInsets.zero
        cell.post = table[indexPath.row]
        
        cell.user = users[indexPath.row]
        
        return cell
}


class importPosts {
    var userID: String?
    var userGroup: String?
    var userComment: String?
    var userTime: Int?
    var userLikes: Int?
    var commentId: String?
    var placeID: String?
    var kommentarCount: Int?
    var id: String?
    
    var likeCount: Int?
    var likes: Dictionary<String, Any>?
    var isLiked: Bool?
    
    init(dictionary: [String: Any], key: String) {
        
        userID = dictionary["userID"] as? String
        userComment = dictionary["userComment"] as? String
        userGroup = dictionary["userGroup"] as? String
        userTime = dictionary["userTime"] as? Int
        userLikes = dictionary["userLikes"] as? Int
        commentId = dictionary["commentId"] as? String
        placeID = dictionary["placeID"] as? String
        kommentarCount = dictionary["kommentarCount"] as? Int
       
        id = key
        
        likeCount = dictionary["likeCount"] as? Int
        likes = dictionary["likes"] as? Dictionary<String, Any>
        
        ViewComments.commentIDNew = commentId!
        
        if let currentUserUid = Auth.auth().currentUser?.uid {
            if let likes = self.likes {
                isLiked = likes[currentUserUid] != nil
            }
        }
        
        
    }
    
}
lztngnrs

lztngnrs1#

按照注解中的建议,创建一个父结构体,其中分别包含一个用户和一个帖子

struct UserData {
    let user: UserModel
    let post: importPosts
}

旁注:请将结构体/类命名为大写,为什么不简单地命名为UserPost呢?
创建数据源数组

var users = [UserData]()

修改fetchUser以在完成处理程序中传递新用户

func fetchUser(uid: String, completed: @escaping (UserModel) -> Void) {
    ref = Database.database().reference().child("user").child(uid).child("userInformation")
    ref.observe(.value) { (snapshot) in
        guard let dic = snapshot.value as? [String: Any] else { return }
        let newUser = UserModel(dictionary: dic)
        completed(newUser)
    }
}

还可以修改postsLaden,将post和关联的用户分配给模型

func postsLaden() {
    //dic = [:] 
    //let neueArray: [String] = [] seems to be unused

    for groupId in myFeed.myArray1[0..<myFeed.myArray1.count] {
        
        let placeIdFromSearch = ViewController.placeidUebertragen
        ref = Database.database().reference().child("placeID/\(groupId)")
        ref.observe(DataEventType.childAdded, with: { snapshot in
            
            guard let dic = snapshot.value as? [String: Any] else { return }
            let newPost = importPosts(dictionary: dic, key: snapshot.key)
            guard let userUid = newPost.userID else { return }

            self.fetchUser(uid: userUid, completed: { user in
                self.users.insert(UserData(user: user, post: newPost), at: 0)
                self.users.sort($0.user.userTime ?? 0 > $1.user.userTime ?? 0)    
                self.tableView.reloadData()
            })
        }
        )}
    
}

最后修改cellForRow

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        cell.layoutMargins = UIEdgeInsets.zero
        let user = users[indexPath.row]
        cell.post = user.post
        cell.user = user.user
        
        return cell
}

还有一个附带说明:在循环中多次排序和重载表视图会产生不必要的开销。您可以添加DispatchGroup,以便在完成时一次地排序和重载数据。关于 expensive:在数据库中,Post是否可以保存对user的完整引用以避免第二次提取?例如,Core Data可以。

相关问题