swift 显示带有自定义单元格的警报

swift show alert with custom cell

我有一个自定义单元格。它有一个 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)
    }
}

但是当我在 tableview 中单击我的保存按钮时,它成功地保存了图像并预热:

Warning: Attempt to present <UIAlertController: 0x7fa452f74ee0> on <Test.ViewController: 0x7fa452f56f40> whose view is not in the window hierarchy!

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

我会使用委托来解决这个问题: 在您的自定义单元格中添加此代码

var delegate: UIViewController?

并在您的 tableView(tableView: cellForRowAtIndexPath) 中添加这一行:

cell.delegate = self

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