首页 > 解决方案 > 如何将保存按钮设置为 swift 5?

问题描述

我正在为 iOS 创建一个壁纸应用程序。我已经创建了一个 UIImageView,但我坚持保存图像。我已经解决了权限,但无法让用户保存图像。我自己创建了保存按钮,但我不知道要从用户图像库中的图像数组中保存任何图像。

到目前为止,这是我的代码:

class ViewController: UIViewController {

    @IBOutlet var imageview: [UIScrollView]!

    @IBOutlet weak var saveButton: UIButton!

    @IBAction func saveButtonPressed(_ sender: UIButton) {
      // TODO: - How to save the image here 
    }

    let scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.isPagingEnabled = true
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        return scroll
    }()

    var imageArray = [UIImage]()

    func setupImages(_ images: [UIImage]){
        for i in 0..<images.count {
            let imageView = UIImageView()
            imageView.image = images[i]
            let xPosition = UIScreen.main.bounds.width * CGFloat(i)
            imageView.frame = CGRect(x: xPosition, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
            imageView.contentMode = .scaleAspectFit

            scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
            scrollView.addSubview(imageView)
            //scrollView.delegate = (self as! UIScrollViewDelegate)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(scrollView)

        imageArray = [#imageLiteral(resourceName: "1"),#imageLiteral(resourceName: "10"),#imageLiteral(resourceName: "9"),#imageLiteral(resourceName: "8"),#imageLiteral(resourceName: "3")]

        setupImages(imageArray)
    }
}

标签: iosswift

解决方案


您将需要添加一个saveImage函数:

func saveImage(image: UIImage) -> Bool {
    guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
        return false
    }

    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }

    do {
        try data.write(to: directory.appendingPathComponent("fileName.png")!)
        return true
    } catch {   
        print(error.localizedDescription)
        return false
    }
}

然后在saveButtonPressed

let success = saveImage(image: imageArray[0])
print("Did \(success ? "" : "not ")store image successfully")

您需要添加一些逻辑来实际选择图像。


推荐阅读