错误:无法将类型'(_,_) - > Void'的值转换为期望的参数类型'((UIAlertAction) - > Void)?'
问题描述:
我在我的Main.storyboard
中创建了一个按钮,其名称(var
)名称为deleteButton
。此按钮位于每个单元格中。错误:无法将类型'(_,_) - > Void'的值转换为期望的参数类型'((UIAlertAction) - > Void)?'
当用户按下按钮时,会弹出警告以确认删除。这是代码。
@IBAction func deletePinpoint(sender: UIButton) {
let alertController = UIAlertController(title: "Delete pinpoint", message: "Do you want to delete this pinpoint?", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action, indexPath) -> Void in
if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
let pinpointToDelete = self.fetchResultController.objectAtIndexPath(sender.tag) as! Pinpoints
managedObjectContext.deleteObject(pinpointToDelete)
do {
try managedObjectContext.save()
} catch {
print(error)
}
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
在cellForRowAtIndexPath:
方法,我宣布这条线:
cell.deleteButton.tag = indexPath.row
我得到的错误3号线(含alertController.addAction
开始)说:
Cannot convert value of type '(_, _) -> Void' to expected argument type '((UIAlertAction) -> Void)?'
我如何解决这个问题?
答
处理程序的参数UIAlertAction
构造函数将选定的操作对象作为其唯一参数。
取而代之的是:
alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (action, indexPath) -> Void in
你会想这样的:
alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction) -> Void in
该错误然后去了,我得到'(sender.tag)错误'说**不能转换价值类型'Int'到期望的参数类型'NSIndexPath'**。 –
你必须创建一个NSIndexPath对象传递给objectAtIndexPath。让indexPath = NSIndexPath(forRow:sender.tag,inSection:0)然后将indexpath设置为objectAtIndexPath(indexPath) – Sebastian
完美!这工作:)) –