多亏了airplay音频systemName表情符号,我做出了一个不错的图标
Button(action: {
showAirplay()
}, label: {
Image(systemName: "airplayaudio")
.imageScale(.large)
})
func showAirplay() {
???
}
但是我不知道如何显示著名的菜单:
最佳答案
终于我设法自己解决了: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){ // copied from https://stackoverflow.com/a/44909445/7974174
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) // (important to be consistent with this frame, like that it is nicely centered... see button.frame in AirPlayViewController)
}
}
}
关于ios - 如何显示AirPlay菜单SwiftUI,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60079607/