【问题标题】:How to add a button to access photo gallery to keyboard in swift?如何快速添加按钮以访问照片库到键盘?
【发布时间】:2019-09-29 13:09:15
【问题描述】:

我正在构建一个聊天应用程序,我想添加发送图像的机会。这就是为什么我想在键盘上添加一个快捷方式来访问画廊或手机的相机。

我在本机键盘类型 (https://developer.apple.com/documentation/uikit/uikeyboardtype) 中看不到它,所以我想我必须以编程方式进行。

我在 stackOverflow 和互联网上都没有找到任何关于它的信息。

我希望能够使用像 iMessage 中那样的键盘。

【问题讨论】:

标签: ios swift keyboard gallery


【解决方案1】:

您可以通过编辑 NSLayoutConstraint 常量在键盘上方创建自己的视图。这是一个示例故事板。

storyboard and constraints

然后:

  • 将您的 NSLayoutConstraint 连接到视图控制器

@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) } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多