8

我已经开始MPVolumeView在我的应用程序中使用,但是 Air Play 按钮根本没有出现。即使我有不止一台 Air Play 设备可用于将我的AVPlayer音频发送到网络上。例如,如果从控制中心检查 Air Play,就可以看到这些。

这是我的代码:

myVolumeView = [MPVolumeView new];
[myVolumeView setShowsVolumeSlider:YES];
[myVolumeView setShowsRouteButton:YES];
myVolumeView.frame = _volumePanel.bounds;
[myVolumeView sizeToFit];
_myVolumeView.autoresizingMask = UIAutoresizingFlexibleWidth;
[_volumePanel addSubview:myVolumeView];

很简单的东西。我有一个AVPlayer运行一些音乐的,就是这样。有趣的是,如果我从控制中心选择另一个 Air Play 设备,它会强制 Air Play 按钮出现在我的应用程序中MPVolumeView,但这有点小故障。

如果在 Xcode 中单击控制台上方的 Debug Hierarchy Mode 按钮,我可以在我的 UI 中看到 Air Play 按钮,但它的 Alpha 为 0。

4

2 回答 2

2

这是一个完整而彻底的黑客,但它有效

   MPVolumeView* airplayButton = [[MPVolumeView alloc] init];

   for (UIButton *button in airplayButton.subviews)
    {
        if ([button isKindOfClass:[UIButton class]])
        {
            [button addObserver:self forKeyPath:@"alpha" options:NSKeyValueObservingOptionNew context:nil];
        }
    }

然后在观察者

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([object isKindOfClass:[UIButton class]] && [[change valueForKey:NSKeyValueChangeNewKey] intValue] != 1)
    {
        UIButton *airplay = (UIButton *)object;
        [airplay setAlpha:1.0];
    }
}

不要忘记在 dealloc 中关闭观察者

- (void)dealloc
{    
    for (UIButton *button in _airplayButton.subviews)
    {
        if ([button isKindOfClass:[UIButton class]])
        {
            [button removeObserver:self forKeyPath:@"alpha"];
            break;
        }
    }
}
于 2017-08-01T23:48:57.577 回答
0

[迅捷版]

创建以下函数:

    func fixAirPlayButton() {
        guard let routeButton = airPlayButton.subviews.filter({$0 is UIButton}).first else { return }
        routeButton.addObserver(self, forKeyPath: "alpha", options: .new, context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        guard let btnObject = object as? UIButton, let change = change else { return}
        guard let newChange = change[NSKeyValueChangeKey.newKey] as? Int, newChange != 1 else { return }
        btnObject.alpha = 1.0
    }

    func removeAirPlayButtonFix() {
        guard let routeButton = airPlayButton.subviews.filter({$0 is UIButton}).first else { return }
        routeButton.removeObserver(self, forKeyPath: "alpha")
    }

并在需要时使用它们,例如:

    let airPlayButton = MPVolumeView(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()
        fixAirPlayButton()
    }

    deinit {
        removeAirPlayButtonFix()
    }
于 2019-06-14T23:04:54.627 回答