簡體   English   中英

如何在swift中添加一個按鈕來訪問照片庫到鍵盤?

[英]How to add a button to access photo gallery to keyboard in swift?

我正在構建一個聊天應用程序,我想添加發送圖像的機會。 這就是為什么我想在鍵盤上添加一個快捷方式來訪問圖庫或手機的相機。

我沒有在原生鍵盤類型( https://developer.apple.com/documentation/uikit/uikeyboardtype )中看到它,所以我想我要以編程方式進行。

我在stackOverflow上和互聯網上都沒有發現它。

我想要訪問類似於iMessage中可用的鍵盤。

您可以通過編輯NSLayoutConstraint常量在鍵盤上方創建自己的視圖。 這是一個示例故事板。

故事板和約束

然后:

  • 將NSLayoutConstraint連接到View Controller

@IBOutlet weak var overKeyboardViewBottomConstraint: NSLayoutConstraint!

  • 在viewDidLoad方法中添加鍵盤偵聽器:

      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) 
  • 為鍵盤創建選擇器

    @objc func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { UIView.animate(withDuration: 0.5) { [unowned self, keyboardSize] in self.overKeyboardViewBottomConstraint.constant = keyboardSize.height self.view.layoutIfNeeded() } } } @objc func keyboardWillHide(notification: Notification) { UIView.animate(withDuration: 0.5) { [unowned self] in self.overKeyboardViewBottomConstraint.constant = 0 self.view.layoutIfNeeded() } }

  • 然后你的相機IBAction

    @IBAction func cameraAction(_ sender: Any) { let photos = PHPhotoLibrary.authorizationStatus() switch photos { case .notDetermined: print("not determined") PHPhotoLibrary.requestAuthorization({status in if status == .authorized{ self.showGallery() } else { print("access denied") } }) case .authorized: print("authorized") self.showGallery() case .denied: print("denied") default: break } }

  • 最后你的畫廊功能

    func showGallery() { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary; imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM