在swift中保存图片到相册
来源:互联网 发布:淘宝新店多久有流量 编辑:程序博客网 时间:2024/05/21 07:07
本来是没有必要把这么小的一个知识点写到博客中的,但是,由于OC中的一些语法在swift中实现的时候有些特别,所以单独写下来到博客中,希望能够帮助到有需要的同学。
1.OC中的写法
在OC中,我们需要保存图片到相册需要调用这个方法:
void UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo);
想来大家也都看过这个方法的头文件,在头文件中有这样一段话
// Adds a photo to the saved photos album. The optional completionSelector should have the form:// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
意思是:想要将一张照片保存到相册中,这个可选的完成方法需要按照下面那个方法的格式来定义。
所以,我们在OC中通常都是直接将这个方法拷贝出来,直接实现这个方法,举个栗子:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UIImageWriteToSavedPhotosAlbum(self.iconView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);}- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { if (error) { NSLog(@"保存出错"); return; } NSLog(@"保存成功");}
在上面这个栗子中,我通过手指触摸事件,将事先定义好的iconView中的图像保存到相册中。
而同样一个栗子,在Swift中应该怎么样实现呢?
2.swift中的写法
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { UIImageWriteToSavedPhotosAlbum(iconView.image, self, "image:didFinishSavingWithError:contextInfo:", nil)} func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) { println("---") if didFinishSavingWithError != nil { println("错误") return } println("OK")}
同样的栗子,swift中的实现如上,在swift中,我们跳到头文件会发现是这样的,
// Adds a photo to the saved photos album. The optional completionSelector should have the form:// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
还是OC中那一套,苹果并没有帮我们写好swift下的代码格式应该怎么写,所以很多人对此应该怎么使用会产生许多的疑惑,其实,就是像上面那样,将参数一一对应,以swift中函数的写法写出来就可以了。
另外补充一点小知识点:
上面的那个方法我们还可以这么写,
// 提示:参数 空格 参数别名: 类型func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) { println("---")// if didFinishSavingWithError != nil { if error != nil { println("错误") return } println("OK")}
类似这样的格式:(参数 参数别名: 类型)didFinishSavingWithError error: NSError?
在外部调用时,显示的是didFinishSavingWithError这个参数名
而在内部使用时,显示的是error这个参数别名,方便我们的使用,也更加类似OC中的写法。
0 0
- 在swift中保存图片到相册
- 在手机相册中保存图片失败
- [iOS]APP中保存图片到相册时崩溃
- iPhone中保存当前view到相册
- 在ios中保存图片到照片库
- 在SQLServer中保存和输出图片
- 在中保存和输出图片
- 在数据库中保存和读取图片
- Andorid在指定文件夹中保存图片
- CImage在OnPaint()函数中保存图片
- Access中保存图片
- PB中保存图片
- android 中保存图片
- PB中保存图片
- 存图片和视频到iPhone相册
- VB.NET Winform 中保存图片到数据库中
- android中保存Bitmap图片到指定文件夹中的方法
- android中保存Bitmap图片到指定文件夹中的方法
- UIViewController总结
- PHP - WIN2003下修复PHP远程DoS漏洞(PHP Multipart/form-data remote dos Vulnerability)
- MyEclipse中文注释乱码解决
- 黑马程序员_java基础之多线程
- MongoDB的简介和使用
- 在swift中保存图片到相册
- Java-----5、面向对象(上)
- 浅层次理解Java Arrays.sort()函数
- 小混混n多天不提编程,深刻反思
- oracle 导入导出拾遗
- yum [Errno 256] No more mirrors to try 解决方法
- iOS UITextfield不弹出键盘 使用自定义键盘
- POJ 1106 Transmitters(计算几何 极角排序啊)
- 用到的drawable selector和shape自定义