相冊選擇照片或拍照(Swift)

今天又做了從相冊選擇照片或者拍照,好久不做了。有些淡忘,去網上找了,有些凌亂,所以決定自己稍稍整理下。

1.判斷相機是否可用,如果可用就有拍照選項,反正則沒有。

let actionSheet: UIActionSheet
    // 判斷相機是否可用
    if UIImagePickerController.isSourceTypeAvailable(.Camera) {
      actionSheet = UIActionSheet(title: "請選擇頭像來源", delegate: self,
                                  cancelButtonTitle: "取消", destructiveButtonTitle: nil,
                                  otherButtonTitles: "從相冊選擇", "拍照")
    } else {
      actionSheet = UIActionSheet(title: "請選擇頭像來源", delegate: self,
                                  cancelButtonTitle: "取消", destructiveButtonTitle: nil,
                                  otherButtonTitles: "從相冊選擇")
    }
    actionSheet.showInView(view)
2.實現UIActionSheetDelegate,判斷所選擇的項

// MARK: - UIActionSheetDelegate
extension AccountViewController: UIActionSheetDelegate {
  func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
    print(buttonIndex)
    var sourceType: UIImagePickerControllerSourceType = .PhotoLibrary
    switch buttonIndex {
    case 1: // 從相冊選擇
      sourceType = .PhotoLibrary
    case 2: // 拍照
      sourceType = .Camera
    default:
      return
    }
    let pickerVC = UIImagePickerController()
    pickerVC.view.backgroundColor = UIColor.whiteColor()
    pickerVC.delegate = self
    pickerVC.allowsEditing = true
    pickerVC.sourceType = sourceType
    presentViewController(pickerVC, animated: true, completion: nil)
  }
}
3.分別對確定和取消事件做處理
// MARK: - UIImagePickerControllerDelegate、UINavigationControllerDelegate
extension AccountViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  func imagePickerController(picker: UIImagePickerController,
                             didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    dismissViewControllerAnimated(true, completion: nil)
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
      headerView.setHeadImage(image)
    }
  }
  func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    dismissViewControllerAnimated(true, completion: nil)
  }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容