我目前在使用 Swift 2编写的Xcode 7.2上运行的iOS 9.2应用程序中有一个侧边栏菜单,允许用户加载哪些数据来填充视图.我正在使用SWRevealViewController来创建侧边栏.我有一个容器视图控制器,它有头版和侧边栏页面,列出了用户拥有的所有选项.每次用户从侧边栏表中选择一个单元格时,它都会执行一个允许刷新首页的segue.我想要做的是允许用户长按删除表格中的单元格.我想显示一个AlertViewController以确认用户的决定,如果选择“是”,我想删除该单元格,并选择表格中的第一个项目.我试过按照 Long press on UITableView的说明进行操作
但我一直收到错误“无法识别的选择器发送到实例”
这是我用于在cellForRowAtIndexPath函数中设置gestureRecognizer的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell;
cell.textLabel!.text = tableArray[indexPath.row];
let holdToDelete = UILongPressGestureRecognizer(target: cell, action: "longPressDelete");
holdToDelete.minimumPressDuration = 1.00;
cell.addGestureRecognizer(holdToDelete);
return cell;
}
这是longPressDelete函数:
func longPressDelete(sender: UILongPressGestureRecognizer) {
let alert: UIAlertController = UIAlertController(title: "Please Confirm", message: "Are you sure you want to delete this car from your database?", preferredStyle: .Alert);
alert.addAction(UIAlertAction(title: "Yes", style: .Destructive, handler: { (UIAlertAction) -> Void in
if let tv = self.tableView {
let point: CGPoint = sender.locationInView(self.tableView);
let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(point)!;
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade);
NSUserDefaults.standardUserDefaults().removeObjectForKey("fillUp" + tableArray[indexPath.row]);
NSUserDefaults.standardUserDefaults().removeObjectForKey("services" + tableArray[indexPath.row]);
tableArray.removeAtIndex(indexPath.row);
NSUserDefaults.standardUserDefaults().setObject(tableArray, forKey: "cars");
self.deleted = true;
self.performSegueWithIdentifier("tableToDashboard", sender: self);
}
}));
alert.addAction(UIAlertAction(title: "No", style: .Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
这是prepareForSegue函数:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (deleted) {
let indexPath: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0);
fillUpKey = "fillUp" + tableArray[indexPath.row];
servicesKey = "services" + tableArray[indexPath.row];
localFillUpArray = [fillUp]();
} else {
let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!;
fillUpKey = "fillUp" + tableArray[indexPath.row];
servicesKey = "services" + tableArray[indexPath.row];
localFillUpArray = [fillUp]();
}
}
我想要发生的是用户删除单元格中的项目,然后应用程序在从其他来源加载信息后执行到前面屏幕的segue.感谢您花时间阅读本文并提供答案.我希望我没有在某个地方犯过新手的错误.
最佳答案 选择器不正确
let holdToDelete = UILongPressGestureRecognizer(target: self,
action: "longPressDelete:");
>:在longPressDelete之后指示方法func longPressDelete(sender:UILongPressGestureRecognizer)实际上接受参数.
> self for target,假设选择器属于注册它的同一个类.
当前选择器“longPressDelete”将匹配没有参数的方法签名:
func longPressDelete() { }