gpt4 book ai didi

swift - 使用 Firebase Firestore 更新 TableViewCell 中的按钮 UI

转载 作者:行者123 更新时间:2023-11-30 11:37:18 25 4
gpt4 key购买 nike

我的应用中的“关注”按钮和“点赞”按钮也遇到同样的问题。

我在 Firebase Firestore 文档中看到了如何在按下时添加数据以及如何删除记录,但是,我在加载 View 时更新要选择或不选择的按钮的初始状态时遇到问题。

这会在 awakeWithNib 中完成吗?您会添加一个快照监听器吗?

FollowerCell.swift

class FollowerCell: UITableViewCell {

// MARK: - Outlets
@IBOutlet weak var friendImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var followButton: SpringButton!

// MARK: - Variables
var userId:String!
var db:Firestore!

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
friendImageView.layer.masksToBounds = true

db = Firestore.firestore()

self.setFollowingButton()
}

// MARK: - Functions
func setFollowingButton() {
if let currentUser = Auth.auth().currentUser {
let followerDB = db.collection("users").document(currentUser.uid).collection("followers").whereField("follower", isEqualTo: true)
followerDB.getDocuments { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error)")
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
self.followButton.isSelected = true
})
}
}
}
}

@IBAction func followButtonPressed(_ sender: UIButton) {
if followButton.isSelected == true {
followButton.isSelected = false
// add follower
if let user = Auth.auth().currentUser {
Firestore.firestore().collection("users").document(user.uid).collection("following").document("\(userId!)").setData([
"name":self.nameLabel.text ?? "",
"following":true
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("\(self.userId!) added to followers")
}
}
}
} else {
followButton.isSelected = true
// delete following
if let user = Auth.auth().currentUser {
Firestore.firestore().collection("users").document(user.uid).collection("following").document("\(userId!)").delete() { err in
if let err = err {
print("Error removing document: \(err)")
} else {
print("\(self.userId!) successfully removed!")
}
}
}
}

}

最佳答案

class FollowersTableViewController: UITableViewController {

// MARK: - Variables
var db:Firestore!
let storage = Storage.storage().reference()
var followerArray = [User]()
var followingArray = [String]()

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

db = Firestore.firestore()

SVProgressHUD.show()
getFollowers()
getFollowing()

self.tableView.reloadData()

}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "followerCell", for: indexPath) as! FollowerCell

// Configure the cell...
let user = followerArray[indexPath.row]

cell.nameLabel.text = user.name
cell.userId = user.documentId
// Set follow button state
if followingArray.contains(cell.userId) {
cell.followButton.isSelected = false
} else {
cell.followButton.isSelected = true
}

let userImageRef = storage.child("\(user.documentId)"+"/profile_pic.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
userImageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
if let error = error {
// Uh-oh, an error occurred! Display Default image
print("Error - unable to download image: \(error)")
cell.friendImageView.image = UIImage(named: "userProfileGray")
} else {
// Data for "locationImages/(locationId).jpg" is returned
cell.friendImageView.image = UIImage(data: data!)
}
SVProgressHUD.dismiss()
}

return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 71
}

// MARK: - Functions
func getFollowers() {
if let user = Auth.auth().currentUser {
let followingDB = db.collection("users").document("\(user.uid)").collection("followers").whereField("follower", isEqualTo: true)
followingDB.getDocuments { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error)")
} else {
for document in (querySnapshot?.documents)! {
self.followerArray.append(User(name: document["name"] as! String, documentId: document.documentID))
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}

func getFollowing() {
if let currentUser = Auth.auth().currentUser {
let followingDB = db.collection("users").document(currentUser.uid).collection("following").whereField("following", isEqualTo: true)
followingDB.getDocuments { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error)")
} else {
for document in (querySnapshot?.documents)! {
self.followingArray.append(document.documentID)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}

}

关于swift - 使用 Firebase Firestore 更新 TableViewCell 中的按钮 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49609671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com