问题描述
我正在开发基于位置的提醒应用。我显示用户在表视图上创建的所有提醒。我也在每个单元格上都有 UISwitch 。我希望 UISwitch 单独禁用/启用提醒,而不是所有通知。我想不通。
extension MainViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return self.items?.count ?? 0
}
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell",for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell",for: indexPath) as! itemTableViewCell
let item = self.items![indexPath.row]
cell.itemTitle?.text = item.itemName
cell.itemSubTitle?.text = item.itemDescription
//switch
let swicthView = UISwitch(frame: .zero)
swicthView.onTintColor = UIColor (named: "DingerBlue")
swicthView.seton(true,animated: true)
swicthView.tag = indexPath.row
swicthView.addTarget(self,action: #selector(self.SwitchBtn(_:)),for: .valueChanged)
cell.accessoryView = swicthView
let itemToRemove = self.items![indexPath.row]
let notifToRemove: String = itemToRemove.notifID!
return cell
}
@objc func switchDidChanged(_ sender: UISwitch){
print("Switch value is \(sender.isOn)")
if(sender.isOn){
print("on")
UIApplication.shared.registerForRemoteNotifications()
}
else{
print("Off")
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notifToRemove])
}
}
}
解决方法
我相信您的代码不起作用,因为单元格被重用,并且特定单元格上的操作应该从单元格类而不是从 ViewController 处理。将此代码移至 UITableViewCell
代码中。
let swicthView = UISwitch(frame: .zero)
swicthView.onTintColor = UIColor (named: "DingerBlue")
swicthView.setOn(true,animated: true)
swicthView.tag = switchViewTag!
swicthView.addTarget(self,action: #selector(self.SwitchBtn(_:)),for: .valueChanged)
@objc func switchDidChanged(_ sender: UISwitch){
print("Switch value is \(sender.isOn)")
if(sender.isOn){
print("on")
UIApplication.shared.registerForRemoteNotifications()
}
else{
print("Off")
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notifToRemove])
}
}
并在 UITableViewCell
weak var switchViewTag: Int?
将您的 cellForRowAt
委托方法修改为
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell",for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell",for: indexPath) as! itemTableViewCell
let item = self.items![indexPath.row]
cell.itemTitle?.text = item.itemName
cell.itemSubTitle?.text = item.itemDescription
cell.switchViewTag = indexPath.row
return cell
}