【问题标题】:swift show alert with custom cell使用自定义单元格快速显示警报
【发布时间】:2015-12-11 09:00:19
【问题描述】:

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

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

【问题讨论】:

    标签: swift uitableview uialertcontroller custom-cell


    【解决方案1】:

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

    var delegate: UIViewController?
    

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

    cell.delegate = self
    

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

    【讨论】:

    • 您可能希望将委托对象设为弱变量以避免数据泄漏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多