我正在开发一个考勤应用程序,该应用程序将其所有数据上传并存储在 firebase 中。大多数事情目前都在工作,除了有时在俱乐部的学生阵列中按下开关时,阵列中的 2 个开关会激活,但按下开关时通常发送的信息只会发送给我实际按下的开关.
这是 TableView 单元格代码:
import UIKit
import Firebase
class StudentCell: UITableViewCell {
var student: Student? { didSet { self.updateUI() }}
@IBOutlet weak var lblStudentName: UILabel!
@IBOutlet weak var lblStudentId: UILabel!
@IBOutlet weak var lblStudentAttending: UISwitch!
let ref = Database.database().reference()
var user: Student! {
didSet{
lblStudentName.text = user.FullName()
lblStudentId.text = user.StudentId
lblStudentAttending.isOn = false
}
}
var switchReference: DatabaseReference?
var switchHandle: DatabaseHandle?
func stopObservation() {
if let handle = switchHandle {
switchReference?.removeObserver(withHandle: handle)
}
}
func startObservation() {
stopObservation()
if let uid = student?.StudentId {
switchReference = ref.child("attendance").child(Global.shared.currentDate).child(uid)
switchReference?.observe(.value, with: { [weak self] (snapshot: DataSnapshot) in
DispatchQueue.main.async {
let isOn = (snapshot.value as? Bool) ?? false
self?.lblStudentAttending.isOn = isOn
}
})
}
}
func updateUI() {
startObservation()
self.lblStudentName.text = self.student?.FullName() ?? ""
self.lblStudentId.text = self.student?.StudentId ?? ""
}
@IBAction func `switch`(_ sender: UISwitch) {
switchReference?.setValue(sender.isOn)
}
}
有谁知道为什么会这样?如果您需要更多信息,请访问。 TIA-Ben
最佳答案
Does anyone know why this might be happening?
表格重复使用它们的单元格,这样它们就不必不断分配新的单元格,当用户试图快速滚动浏览大量行时,这样做的成本很高。您正在为每个单元格中的开关设置一个观察器,这意味着您需要在单元格不再可见时停止观察该开关。您可能会在单元格的 prepareForReuse()
方法中调用 stopObservation()
并解决问题。
更好的解决方案是完全避免观察开关,而是使用控件通常用于在用户更改其值时触发操作的目标/操作机制。这样您就不必担心不断地开始和停止观察。
关于arrays - 当仅按下一个 Swift 时,阵列中的多个开关被激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513679/