Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I trigger the click event on AVRoutePickerView using swift

Tags:

ios

swift

airplay

Using AVRoutePickerView, I'm able to do the Airplay programmatically upon tapping the Airplay icon. Now I want, on viewDidLoad it should initialize the AVRoutePickerView and even tap the airplay icon (no need to manually tap on icon).

Here's my small piece of code to display Airplay icon on UIView

let routePV = AVRoutePickerView(frame: CGRect(x: 30.0, y: 150.0, width: 30.0, height: 30.0)) routePV = UIColor.clear
self.view.addSubview(routePV)

I'm really not sure how to trigger tap on viewdidload ?

Thanks

like image 308
janubhai Avatar asked Dec 22 '22 23:12

janubhai


2 Answers

This is possible. However I must caution it is likely to be quite unexpected behavior to present this interface without user interaction. I’d recommend only doing this as a direct result of the user intending to present this interface.

Make sure you have added it to your view hierarchy.

let routePickerView = AVRoutePickerView()
view.addSubview(routePickerView)

If desired, you can hide it.

routePickerView.isHidden = true

Then to present the route picker interface, trigger touchUpInside on its UIButton:

if let routePickerButton = routePickerView.subviews.first(where: { $0 is UIButton }) as? UIButton {
    routePickerButton.sendActions(for: .touchUpInside)
}

Do note that this could stop working in a future iOS release.

like image 170
Jordan H Avatar answered Dec 29 '22 11:12

Jordan H


I prefer to use an extension:

fileprivate extension AVRoutePickerView {
    func present() {
        let routePickerButton = subviews.first(where: { $0 is UIButton }) as? UIButton
        routePickerButton?.sendActions(for: .touchUpInside)
    }
}

Example implementation:

class RandomViewController: UIViewController {

    ...

    private lazy var routePickerView = { 
        let routePickerView = AVRoutePickerView(frame: .zero)
        routePickerView.isHidden = true
        view.addSubview(routePickerView)
        return routePickerView
    }

    ...

    @IBAction func presentPickerView(_ sender: UIButton) {
        routePickerView.present()
    }
}
like image 24
Stefan Avatar answered Dec 29 '22 12:12

Stefan