Swift 使用自定义单元格快速显示警报

Swift 使用自定义单元格快速显示警报,swift,uitableview,uialertcontroller,custom-cell,Swift,Uitableview,Uialertcontroller,Custom Cell,我有一个定制的手机。它有一个UIImageView和一个按钮。当我单击该按钮时,我的应用程序将把我的图像保存到相册并显示结果警报 这是我的代码: @IBAction func saveImage(sender: UIButton) { UIImageWriteToSavedPhotosAlbum(self.photo.image!, self, "saveImageToLibrary:didFinishSavingWithError:contextInfo:", nil)

我有一个定制的手机。它有一个UIImageView和一个按钮。当我单击该按钮时,我的应用程序将把我的图像保存到相册并显示结果警报

这是我的代码:

@IBAction func saveImage(sender: UIButton) {
        UIImageWriteToSavedPhotosAlbum(self.photo.image!, self, "saveImageToLibrary:didFinishSavingWithError:contextInfo:", nil)
    }

func saveImageToLibrary(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
    let vc = ViewController()
    if error == nil {
        let ac = UIAlertController(title: "Saved!", message: "Image has been saved to your photos.", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        vc.presentViewController(ac, animated: true, completion: nil)
    } else {
        let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        vc.presentViewController(ac, animated: true, completion: nil)
    }
}
@IBAction func saveImage(发件人:UIButton){
UIImageWriteToSavedPhotosAlbum(self.photo.image!,self,“保存图像到库:didFinishSavingWithError:contextInfo:”,无)
}
func saveImageToLibrary(图像:UIImage,DidFinishSavingWither错误:NSError?,上下文信息:UnsafePointer){
设vc=ViewController()
如果错误==nil{
让ac=UIAlertController(标题:“已保存!”,消息:“图像已保存到照片中。”,首选样式:。警报)
ac.addAction(UIAlertAction(标题:“确定”,样式:。默认,处理程序:nil))
vc.presentViewController(ac,动画:true,完成:nil)
}否则{
让ac=UIAlertController(标题:“保存错误”,消息:错误?.localizedDescription,首选样式:。警报)
ac.addAction(UIAlertAction(标题:“确定”,样式:。默认,处理程序:nil))
vc.presentViewController(ac,动画:true,完成:nil)
}
}
但当我在tableview中单击“保存”按钮时,它成功地保存了图像,并显示了一个警告:

Warning: Attempt to present <UIAlertController: 0x7fa452f74ee0> on <Test.ViewController: 0x7fa452f56f40> whose view is not in the window hierarchy!
警告:尝试显示其视图不在窗口层次结构中的对象!

如何从自定义单元格调用警报?

我将使用代理解决此问题: 在自定义单元格中添加此代码

var delegate: UIViewController?
并在tableView(tableView:CellForRowatineXpath)中添加以下行:

cell.delegate = self

最后,在saveImageToLibrary实现中,将
vc
替换为
delegate?
。这个是因为您将委托创建为可选变量。

您可能希望使委托对象成为弱变量,以避免数据泄漏