一, 声明相框和按钮
var imageView : UIImageView!
var button : UIButton!
imageView = UIImageView.init(frame: CGRectMake(50, 200, 300, 300))
imageView.backgroundColor = UIColor.cyanColor()
self.view.addSubview(imageView)
imageView.userInteractionEnabled = true
button = UIButton.init(frame: CGRectMake(50, 50, 300, 50))
button.backgroundColor = UIColor.redColor()
button.setTitle("选取本地图片", forState: UIControlState.Normal)
button.addTarget(self,action:#selector(ViewController.huantu),forControlEvents:.TouchUpInside)
self.view.addSubview(button)
二, 创建提示框
extension ViewController {
var selectorController: UIAlertController {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
controller.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil)) // 取消按钮
controller.addAction(UIAlertAction(title: "拍照选择", style: .Default) { action in
self.selectorSourceType(.Camera)
}) // 拍照选择
controller.addAction(UIAlertAction(title: "相册选择", style: .Default) { action in
self.selectorSourceType(.PhotoLibrary)
}) // 相册选择
return controller
}
func huantu(){
presentViewController(selectorController, animated: true, completion: nil)
}
func selectorSourceType(type: UIImagePickerControllerSourceType) {
imagePickerController.sourceType = type
// 打开图片选择器
presentViewController(imagePickerController, animated: true, completion: nil)
}
}
三, 扩展图片选择和结果返回
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: 图片选择器界面
var imagePickerController: UIImagePickerController {
get {
let imagePicket = UIImagePickerController()
imagePicket.delegate = self
imagePicket.sourceType = .PhotoLibrary
return imagePicket
}
}
// MARK: 当图片选择器选择了一张图片之后回调
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {
dismissViewControllerAnimated(true, completion: nil) // 选中图片, 关闭选择器...这里你也可以 picker.dismissViewControllerAnimated 这样调用...但是效果都是一样的...
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage // 显示图片
imageView.contentMode = .ScaleToFill // 缩放显示, 便于查看全部的图片
}
// MARK: 当点击图片选择器中的取消按钮时回调
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil) // 效果一样的...
}
四, 最终效果