ios - 如何将保存按钮设置为 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)
}
}
解决方案
您将需要添加一个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")
您需要添加一些逻辑来实际选择图像。
推荐阅读
- python - 如何并排绘制图表以进行比较?
- db2 - DB2(版本:11.5.0.1077)命令 LIST ACTIVE DATABASES 不起作用
- c# - 使用 C# Linq 对嵌套对象进行分组和收集
- html - 如何单击网站中的菜单栏选项?
- python - 了解 cdist() 函数
- javascript - 在节点进程中共享变量的最佳方式
- pine-script - 如何为内置函数使用动态长度
- rust - How to get the command behind std::process::Command in Rust?
- java - 在 Java Spring Boot 应用程序中抛出 ClassNotFoundException 的 Groovy 文件
- performance - 在 nativescript/javascript 中运行非阻塞、高性能的活动