最终我自己解决了它:D
就像评论中所说,我必须“嵌入”到UIKit中并在SwiftUI中使用它
首先:
struct AirPlayButton: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<AirPlayButton>) -> UIViewController {
return AirPLayViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<AirPlayButton>) {
}
}
然后是经典的ViewController,我们从很久以前就知道如何显示这个著名的AirPlay菜单弹出窗口:
class AirPLayViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let isDarkMode = self.traitCollection.userInterfaceStyle == .dark
let button = UIButton()
let boldConfig = UIImage.SymbolConfiguration(scale: .large)
let boldSearch = UIImage(systemName: "airplayaudio", withConfiguration: boldConfig)
button.setImage(boldSearch, for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.backgroundColor = .red
button.tintColor = isDarkMode ? .white : .black
button.addTarget(self, action: #selector(self.showAirPlayMenu(_:)), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func showAirPlayMenu(_ sender: UIButton){
let rect = CGRect(x: 0, 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()
}
}
最后,在SwiftUI中只需调用:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World")
AirPlayButton().frame(width: 40, height: 40)
}
}
}