代码之家  ›  专栏  ›  技术社区  ›  Kashif Richard Brightwell

cameraOverlayView中的自定义快门按钮未执行

  •  1
  • Kashif Richard Brightwell  · 技术社区  · 8 年前

    我正在用斯威夫特定制相机。我这样宣布它是全球性的:

    let image = UIImagePickerController()
    

    我已经做了 OverlayVC (UIViewController) 在IB中,制作了一个快门按钮,并将其连接如下:

    @IBAction func shutterTapped(_ sender: Any) {
        print("shutterTapped")
        image.takePicture()
    }
    

    我在演示之前实例化了此覆盖:

    image.delegate = self
    image.sourceType = .camera
    image.cameraDevice = .front
    image.allowsEditing = false
    let overlay = self.storyboard?.instantiateViewController(withIdentifier: "OverlayVC")
    image.cameraOverlayView = overlay?.view
    image.showsCameraControls = false
    self.present(image, animated: true, completion: nil)
    

    现在,当我运行内置设备并点击快门按钮时,我可以在视觉上看到它被点击(淡出/进入),但代码进入 shutterTapped() 从不执行。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Miknash    8 年前

    为什么它没有真正起作用?

    添加视图控制器的视图会删除控制器本身,并且没有人可以实际获取事件。因此,您可以看到视图,但不能看到事件。为了支持这一点:

    enter image description here

    实际与您的代码配合使用的解决方案是:

    image.cameraOverlayView = overlay?.view
    if let viewController  = overlay {
    
        for view in viewController.view.subviews {
            if let button = view as? UIButton {
               button.addTarget(self, action: #selector(self.takePicture), for: UIControlEvents.touchDown)
            }
        }
    }
    

    您还可以向其中添加标签,以便检查哪个按钮是哪个按钮,如果您有更多的按钮。

    替代解决方案:

    创造 UIView 子类及其xib。与您在 OverlayVC 。然后,在添加覆盖时,请使用以下内容:

    image.sourceType = .camera
    image.cameraDevice = .front
    image.allowsEditing = false
    let myOverlay = Bundle.main.loadNibNamed("CameraOverlay", owner: self, options: nil)
    image.cameraOverlayView = myOverlay?.first as! UIView
    image.showsCameraControls = false
    self.present(image, animated: true, completion: nil)
    

    请注意,强制展开应使用 guard if let 铸造到时 UIView视图