iOS – 如何在Swift中显示“AirPlay”popup式菜单?

如何在Swift项目中显示AirPlaypopup式菜单? (像Spotify这样的许多应用程序可以像下面这样显示):

在这里输入图像说明

这是一个可爱的小解决scheme,以使用MPVolumeView的button。

  1. 创build一个MPVolumeView,并将其隐藏在视图层次结构中的某个位置。
  2. 每当你想显示select器:

[[UIApplication sharedApplication] sendAction:NSSelectorFromString(@"_displayAudioRoutePicker") to:myVolumeView from:myView forEvent:nil];

可选3:在iPad上,您需要传递一个UIEvent,否则popup窗口只会进入屏幕的顶部,看起来很乱。 捕获事件- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; 并传递给我们的电话。

毕竟看起来没有简单明了的方法来制作自定义button来显示系统的Airplay菜单。

然而,@totiG指向我一个有趣的资源,我创build了一个脚本,在屏幕的可见区域之外创build标准的音量控制模拟点击Airplaybutton:

 func showAirplay() { let rect = CGRect(x: -100, y: 0, width: 0, height: 0) let airplayVolume = MPVolumeView(frame: rect) airplayVolume.showsVolumeSlider = false self.view.addSubview(airplayVolume) for view: UIView in airplayVolume.subviews { if let button = view as? UIButton { button.sendActions(for: .touchUpInside) break } } airplayVolume.removeFromSuperview() } 

运行此代码后,出现以下popup式菜单:

在这里输入图像说明

我不确定您是否特别想要airplay方面的帮助,或者您是否只想使用该devise的popup式菜单(或两者兼而有之)。 我不熟悉airplay如何与编程配合使用,但是为了创build该风格的popup窗口,可以使用UIAlertController:

 let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) ac.addAction(UIAlertAction(title: "iPhone", style: .default, handler: { (action) in //do airplay stuff that connects to the iPhone })) ac.addAction(UIAlertAction(title: "MacBook Pro", style: .default, handler: { (action) in //do airplay stuff that connects to the MacBook Pro })) ac.addAction(UIAlertAction(title: "Apple TV 3", style: .default, handler: { (action) in //do airplay stuff that connects to the Apple TV 3 })) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(ac, animated: true, completion: nil) 

如果您需要使用AirPlay,请点击以下链接查看Apple播放的文档,以及一些有用的video和文档: https : //developer.apple.com/airplay/