我有一个自定义 UITableView,其中包含我想要使用 UserDefaults 检索和保存的每个单元格中的数据。
我希望当用户点击单元格时调用 didSelectRowAt
,以便我可以检索该特定单元格内的数据。
问题是 didSelectRowAt
没有被调用,我尝试了以下方法:
- 确保没有手势识别器“吃掉”单元格上的点击(我从未添加过手势识别器)。
- 将 Identity Inspector 的“选择”部分设置为“无”和“单选”。
下面是如何设置 ViewController 和 TableView 的屏幕截图:
这是我的代码:
class blueSide: UIViewController, UITableViewDelegate, UITableViewDataSource {
var items : [SosItem] = []
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
ref.observe(.value, with: {
snapshot in
var newItems : [SosItem] = []
for child in snapshot.children {
if let snapshot = child as? DataSnapshot,
let sosItem = SosItem(snapshot: snapshot) {
newItems.append(sosItem)
}
}
self.items = newItems
print(self.items)
self.tableView.reloadData()
})
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let removedItem = items.remove(at: indexPath.row)
let itemsRef = ref.child(removedItem.key.lowercased())
itemsRef.removeValue()
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sosItem = items[indexPath.row]
print(sosItem)
UserDefaults.standard.set(sosItem.clothingDescription, forKey: "clothingDescription")
UserDefaults.standard.set(sosItem.placeName, forKey: "placeName")
UserDefaults.standard.set(sosItem.longitude, forKey: "longitude")
print("Longitude saved!")
UserDefaults.standard.set(sosItem.latitude, forKey: "latitude")
print("Latitude saved!")
print(UserDefaults.standard.value(forKey: "latitude"))
// tableView.deleteRows(at: [indexPath], with: .fade)
// tableView.reloadData()
self.performSegue(withIdentifier: "uberSegue", sender: self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! CustomTableViewCell
//get cell data from Firebase
let sosItem = items[indexPath.row]
cell.descriptionLabel.text = sosItem.clothingDescription
cell.latitudeLabel.text = String(sosItem.latitude)
cell.longitudeLabel.text = String(sosItem.longitude)
cell.locationNameLabel.text = sosItem.placeName
cell.destinationLabel.text = sosItem.dropoffLocation
return cell
}
最佳答案
当 tableView 处于编辑模式、isEditing 属性设置为 true 或调用 canEditRowAt 时,不会调用 didSelectedRowAt 方法 尝试在编辑模式结束时选择一行,作为测试!
关于ios - 无法从 TableViewCell 检索数据,因为未调用 didSelectRowAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240687/