快速显示警报与自定义单元格

时间:2015-12-11 09:00:20

标签: swift uitableview uialertcontroller 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!

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

1 个答案:

答案 0 :(得分:1)

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

var delegate: UIViewController?

并在你的tableView(tableView:cellForRowAtIndexPath)中添加以下行:

cell.delegate = self

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