MPVolumeView的AirPlay按钮没有显示出来。

4

我想使用 MPVolumeView 创建一个AirPlay输出按钮,以便在应用的音频中使用。

MPVolumeView *volumeView = [ [MPVolumeView alloc] initWithFrame:CGRectMake(20, 20, 220, 20)];
    [volumeView setShowsVolumeSlider:NO];
    [volumeView setShowsRouteButton:YES];
    [volumeView sizeToFit];
    [self.view addSubview:volumeView];
    [volumeView release];

没有出现错误或问题,但它没有显示出来,有任何想法吗?
谢谢!


我刚刚使用了你的代码,它运行良好。Airplay按钮出现了,操作也正常...你是将它添加到tableView或其他什么地方了吗? - Tommy Devoy
3个回答

6

可能是因为您将VolumeView放在白色背景上。 Airplay路由按钮在使用之前是白色的(即:当它不通过AirPlay进行路由时),因此如果您将控件放在白色背景上,您将看不到它,但它会响应轻触。 将背景更改为像上面那样的红色,它就会显示出来。


3

不要使用init方法,改用initWithFrame:(CGRect)方法发送消息。看起来视图已经存在,只是它的框架是(0,0,0,0)。

以下是代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    ViewController *vc = [[ViewController alloc] init];
    [vc.view setBackgroundColor:[UIColor redColor]];
    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(20, 20, 200, 50)];
    [volumeView setShowsVolumeSlider:YES];
    [volumeView setShowsRouteButton:YES];
    [volumeView sizeToFit];
    [vc.view addSubview:volumeView];
    UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 200, 50)];
    testLabel.text = @"TESTING";
    [vc.view addSubview:testLabel];
    [self.window setRootViewController:vc];
    [self.window makeKeyAndVisible];
    [vc viewDidLoad];
    return YES;
}

在设备上测试时它可以正常工作:

这里输入图像描述


谢谢,已更新为initWithFrame:CGRectMake(20, 20, 220, 20),但仍然:/ - Peter V
我假设self.view是指向ViewController的主视图的引用?由于一切都编译成功了,所以您已经在头文件中添加了适当的导入语句? - Siddharth Dhingra
是的,self.view与所有其他元素配合使用,没有问题,已导入MediaPlayer/MediaPlayer.h。有什么想法吗? - Peter V
7
检查答案:您不能在模拟器中使用MPVolumeView。 - Siddharth Dhingra

2

当有多个路由可用时,Airplay路由按钮会出现。

我发现一个小技巧,可以让Airplay按钮永久显示:隐藏MPVolumeView路由按钮,取消用户与MPVolumeView的交互,并使用UIButton包装器来定位路由按钮操作。

var airplayRouteButton: UIButton?

private func airPlayButton() -> UIButton {

    let wrapperView = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    wrapperView.setImage(YOUR_AIRPLAY_IMAGE, for: UIControlState.normal)
    wrapperView.backgroundColor = .clear
    wrapperView.addTarget(self, action: #selector(PlayerView.replaceRouteButton), for: UIControlEvents.touchUpInside)

    let volumeView = MPVolumeView(frame: wrapperView.bounds)
    volumeView.showsVolumeSlider = false
    volumeView.showsRouteButton = false
    volumeView.isUserInteractionEnabled = false

    self.airplayRouteButton = volumeView.subviews.filter { $0 is UIButton }.first as? UIButton

    wrapperView.addSubview(volumeView)

    return wrapperView
}

@objc private func replaceRouteButton() {
    airplayRouteButton?.sendActions(for: .touchUpInside)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接