【问题标题】:Persist chosen button images after restart iOS with Swift 3使用 Swift 3 重新启动 iOS 后保留所选按钮图像
【发布时间】:2018-01-13 06:40:59
【问题描述】:

我的屏幕上有多个按钮。

当您单击按钮时,它会调用一个函数,该函数使用 UIImagePickerController 从库或相机中选择图像并将该图像保存到按钮图标中。 (所以基本上是可点击的图片)。

我现在正在尝试添加一些持久性,以便在重新启动应用程序时按钮保存其分配的图像。我还没有找到一个我可以遵循的答案来解释如何实现这一点。

我已将 Core Data 框架添加到我的项目中。任何人都可以建议如何进行。 - 谢谢。

var newPicImg : UIButton?;

@IBOutlet weak var ButtImg1: UIButton!
@IBOutlet weak var ButtImg2: UIButton!
@IBOutlet weak var ButtImg3: UIButton!

按钮:

   @IBAction func chooseImage(_ sender: UIButton) {
    newPicImg = ButtImg1
    picStuff()
}
@IBAction func chooseImage1(_ sender: UIButton) {
    newPicImg = ButtImg2
    picStuff()
}

@IBAction func chooseImage2(_ sender: UIButton) {
    newPicImg = ButtImg3
    picStuff()

}

拍摄/选择图片:

   func picStuff()

{
    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self

    let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action:UIAlertAction)in
        imagePickerController.sourceType = .camera
        self.present(imagePickerController, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {(action:UIAlertAction)in
        imagePickerController.sourceType = .photoLibrary
        self.present(imagePickerController, animated: true, completion: nil)
    }))
    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil ))
    self.present(actionSheet, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    newPicImg?.setImage(image, for: .normal)
    picker.dismiss(animated: true, completion: nil)


}

【问题讨论】:

    标签: ios iphone swift3 ios10 xcode8


    【解决方案1】:

    是的,您可以使用 CoreData 并创建一个数据库来存储图像,然后检索它们。但是,如果您最多只存储 3 张图像,然后可能会更改它们,但总是最多 3 张,这可能会很麻烦。

    也许更简单的解决方案是将图像保存到文档目录,并使用特定名称(如 imageButton1.png)并在必要时检索或替换它们。

    这里有一篇关于如何做到这一点的帖子:

    Save An Image To Application Documents Folder From UIView On IOS

    【讨论】:

    • 感谢零,但这个答案似乎主要基于 Objective-C。从 Swift 3 的角度来看,我认为我需要一些更基本的东西。
    • 不是真的,在同一篇文章中有一个 Swift 版本的答案:stackoverflow.com/a/39062752/4691224
    • 是的,看到了,可惜还是超出了我目前的理解水平。
    • 所以我刚刚发现添加: UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) 到我的 imagepickercontroller 会将任何相机图像保存到照片库中。也许这样做的一种方法是仅依赖存储在库中的图像并引用这些图像?
    • 通过通常的阅读stackoverflow循环,添加代码,删除代码,重复。在 iOS 中保存图像真的这么复杂吗?疯了!
    猜你喜欢
    • 2020-11-15
    • 1970-01-01
    • 2017-12-01
    • 2014-03-05
    • 2020-03-04
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多