ios - 滚动时 Swift UITableViewCell 按钮状态更改

标签 ios swift uitableview tableview

因此,我的 UITableViewCell 中有一个按钮,用于更改状态和更新数据库。但是,当我滚动并返回时,状态处于加载 View 时的原始状态。

如何让状态在滚动后保持变化?

我尝试在 prepareForReuse 中设置状态图像,但没有成功。

// MARK: - Outlets
@IBOutlet weak var locationImage: UIImageView!
@IBOutlet weak var displayName: UILabel!
@IBOutlet weak var countryLabel: UILabel!
@IBOutlet weak var beenHereLabel: SpringLabel!
@IBOutlet weak var needToGoLabel: SpringLabel!
@IBOutlet weak var wavetrotterButton: SpringButton!
@IBOutlet weak var checkmarkButton: SpringButton!

// MARK: - Variables
var db:Firestore!
let selection = UISelectionFeedbackGenerator()
let notification = UINotificationFeedbackGenerator()
var documentId:String!

// MARK: - Nib shown
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

    db = Firestore.firestore()

}

func customInit(displayName: String, id: String, country: String, image: UIImage) {
    self.displayName.text = displayName
    self.documentId = id
    self.countryLabel.text = country
    self.locationImage.image = image
}

// MARK: - Actions
@IBAction func checkmarkButtonPressed(_ sender: UIButton) {
    notification.notificationOccurred(.success)
    checkmarkButton.animation = "pop"
    beenHereLabel.animation = "pop"
    if checkmarkButton.isSelected == true {
        checkmarkButton.animate()
        beenHereLabel.animate()
        checkmarkButton.isSelected = false
        // Delete location surfed
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("surfed").document("\(documentId!)").delete() { err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("\(self.documentId!) successfully removed!")
                }

            }
        }
    } else {
        checkmarkButton.animate()
        beenHereLabel.animate()
        checkmarkButton.isSelected = true
        // Add location surfed
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("surfed").document("\(documentId!)").setData([
                "name":displayName.text ?? "",
                "country":countryLabel.text ?? ""
            ])  { err in
                if let err = err {
                     print("Error writing document: \(err)")
                } else {
                    print("\(self.documentId!) added to surfed locations")
                }
            }
        } 
    }
}

@IBAction func wavetrotterButtonPressed(_ sender: UIButton) {
    notification.notificationOccurred(.success)
    wavetrotterButton.animation = "pop"
    needToGoLabel.animation = "pop"
    if wavetrotterButton.isSelected == true {
        wavetrotterButton.animate()
        needToGoLabel.animate()
        wavetrotterButton.isSelected = false
        // Delete location wantToSurf
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("wantToSurf").document("\(documentId!)").delete() { err in
                if let err = err {
                    print("Error removing document: \(err)")
                } else {
                    print("\(self.documentId!) successfully removed!")
                }
            }
        }
    } else {
        wavetrotterButton.animate()
        needToGoLabel.animate()
        wavetrotterButton.isSelected = true
        // Add location wantToSurf
        if let user = Auth.auth().currentUser {
            Firestore.firestore().collection("users").document(user.uid).collection("wantToSurf").document("\(documentId!)").setData([
                "name":displayName.text ?? "",
                "country":countryLabel.text ?? ""
            ])  { err in
                if let err = err {
                    print("Error writing document: \(err)")
                } else {
                    print("\(self.documentId!) added to surfed locations")
                }
            }
        }
    }
}

LocationResultsTableViewController.swift

   // MARK: - Variables
var listName: String?
var listId: String?
var db:Firestore!
let storage = Storage.storage().reference()
var locationArray = [Location]()
var userSurfedArray = [String]()
var userWantToSurfArray = [String]()
let pullToRefreshControl = UIRefreshControl()
var selectedDocumentId: String?

// MARK: - View Did Load
override func viewDidLoad() {
    super.viewDidLoad()

    self.title = listName

    db = Firestore.firestore()

    SVProgressHUD.show()

    getListLocations()
    getUserSurfedArray()
    getUserWantToSurfArray()

    // Configure the cell to the nib file
    let nib = UINib(nibName: "LocationCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "locationCell")

    self.refreshControl = pullToRefreshControl
    pullToRefreshControl.addTarget(self, action: #selector(refreshTable), for: .valueChanged)

    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

}

// MARK: - View Will Appear
override func viewWillAppear(_ animated: Bool) {
    tableView.reloadData()
}

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return locationArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "locationCell", for: indexPath) as! LocationCell
    // Configure the cell...

    let location = locationArray[indexPath.row]

    cell.documentId = location.documentId

    // Set button states
    if self.userSurfedArray.contains(cell.documentId!) {
        cell.checkmarkButton.isSelected = true
    } else {
        cell.checkmarkButton.isSelected = false
    }

    if self.userWantToSurfArray.contains(cell.documentId!) {
        cell.wavetrotterButton.isSelected = true
    } else {
        cell.wavetrotterButton.isSelected = false
    }

    let locationImageRef = storage.child("locationImages/"+(location.documentId)+".jpg")
    // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
    locationImageRef.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)")
        } else {
            // Data for "locationImages/(locationId).jpg" is returned
            cell.customInit(displayName: location.name, id: location.documentId, country: location.country, image: UIImage(data: data!)!)
        }
        SVProgressHUD.dismiss()
    }

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedDocumentId = locationArray[indexPath.row].documentId
    self.performSegue(withIdentifier: "goToLocationProfileSegue", sender: self)
}

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


// MARK: - Functions
func getListLocations() {
    if Auth.auth().currentUser != nil {
        db.collection("locations").whereField("lists."+listId!, isEqualTo: true).getDocuments() { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                print(querySnapshot?.documents.count ?? "0")
                for document in querySnapshot!.documents {
                    self.locationArray.append(Location(documentId: document.documentID, name: document["name"] as! String, country: document["country"] as! String))
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

func getUserSurfedArray() {
    if let user = Auth.auth().currentUser {
        db.collection("users").document(user.uid).collection("surfed").getDocuments() { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                for document in querySnapshot!.documents {
                    self.userSurfedArray.append(document.documentID)
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

func getUserWantToSurfArray() {
    if let user = Auth.auth().currentUser {
        db.collection("users").document(user.uid).collection("wantToSurf").getDocuments() { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                for document in querySnapshot!.documents {
                    self.userWantToSurfArray.append(document.documentID)
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

最佳答案

这背后的原因是单元格重用,您必须在该 indexPath 处保存按钮的状态,并在 cellForRowAt 中恢复它

关于ios - 滚动时 Swift UITableViewCell 按钮状态更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49653370/

相关文章:

iphone - CSS - iphone中的绝对定位? (phonegap, jqtouch)

ios - 如何将日期(不知道种类)转换为字符串

ios - 核心数据中两个实体之间的不同多对多关系

swift - FMDB 单元测试是否成功创建表未通过

iphone - 如何在UITableView中显示滚动条

ios - SwiftUI VStack 右对齐单个元素

swift - 在无限循环中等待自己,但用户每次都可以取消

swift - GeometryReader 和 .frame 的对齐

swift - 表格单元格未被调用

ios - 使用xib文件的自定义表格 View 的单元格,无法单击/选择/点击