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

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

1.判斷相機(jī)是否可用,如果可用就有拍照選項(xiàng),反正則沒(méi)有。

let actionSheet: UIActionSheet
    // 判斷相機(jī)是否可用
    if UIImagePickerController.isSourceTypeAvailable(.Camera) {
      actionSheet = UIActionSheet(title: "請(qǐng)選擇頭像來(lái)源", delegate: self,
                                  cancelButtonTitle: "取消", destructiveButtonTitle: nil,
                                  otherButtonTitles: "從相冊(cè)選擇", "拍照")
    } else {
      actionSheet = UIActionSheet(title: "請(qǐng)選擇頭像來(lái)源", delegate: self,
                                  cancelButtonTitle: "取消", destructiveButtonTitle: nil,
                                  otherButtonTitles: "從相冊(cè)選擇")
    }
    actionSheet.showInView(view)
2.實(shí)現(xiàn)UIActionSheetDelegate,判斷所選擇的項(xiàng)

// MARK: - UIActionSheetDelegate
extension AccountViewController: UIActionSheetDelegate {
  func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
    print(buttonIndex)
    var sourceType: UIImagePickerControllerSourceType = .PhotoLibrary
    switch buttonIndex {
    case 1: // 從相冊(cè)選擇
      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.分別對(duì)確定和取消事件做處理
// 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)
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容