实现修改头像的功能,首先给给一个图片添加点击事件,在事件处理函数中打开摄像头,自拍,选定照片后修改图片内容。
//图片引用: @IBOutlet weak var goWork: UIButton! override func viewDidLoad() { /////设置允许交互属性 goWorkFace.userInteractionEnabled = true ////添加tapGuestureRecognizer手势 let tapGR1 = UITapGestureRecognizer(target: self,action: "ontapHandler:") goWorkFace.addGestureRecognizer(tapGR1) } //FIXME:上班手势处理函数 func ontapHandler(sender:UITapGestureRecognizer) { ///////todo.... print(“图片被点击”) }
然后在点击处理函数中打开图片选择器。
2 添加相机
先给类增加代理:
UIImagePickerControllerDelegate,UINavigationControllerDelegate
声明类变量:var imagePicker: UIImagePickerController!
修改viewDidLoad():
override func viewDidLoad() { /////设置允许交互属性 goWorkFace.userInteractionEnabled = true ////添加tapGuestureRecognizer手势 let tapGR1 = UITapGestureRecognizer(target: self,action: "ontapHandler:") goWorkFace.addGestureRecognizer(tapGR1) //初始化图片选择器 imagePicker = UIImagePickerController() //检测相机是否可用 let isAvailable = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) //必须首先设置sourceType 然后再设置其他属性 否则会出异常,提示sourceType 必须是 UIImagePickerControllerSourceTypeCamera imagePicker.sourceType = .PhotoLibrary if isAvailable { imagePicker.sourceType = .Camera //如果有前置摄像头则调用前置摄像头 imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.Front //是否显示控制栏 imagePicker.showsCameraControls=true } //是否可编辑 imagePicker.allowsEditing=true //代理 imagePicker.delegate = self }
实现选择完图片后的处理方法:
func imagePickerController(picker: UIImagePickerController!,didFinishPickingImage image: UIImage!,editingInfo: [NSObject : AnyObject]!) { //保存图片 self.goWorkFace.image=image imagePicker.dismissViewControllerAnimated(true){ print("关闭相机返回") } }
自拍头像功能的实现就这点代码了。
注意:
1 如果相机界面的按钮文字默认是英文,要显示中文需要修改project 属性:
2 网上说要想使用相机首先要修改plist文件,在required device capabilities添加一项:still-camera=1。
这个只是用来声明该软件需要具备相机硬件,可不加。