苹果推荐使用MPVolumeView
,所以我想出了这个:
添加volumeSlider
属性:
@property (nonatomic, strong) UISlider *volumeSlider;
初始化MPVolumeView
并添加到您的视图的某个位置(可以隐藏,没有框架,或者因为showsRouteButton = NO
and为空showsVolumeSlider = NO
):
MPVolumeView *volumeView = [MPVolumeView new];
volumeView.showsRouteButton = NO;
volumeView.showsVolumeSlider = NO;
[self.view addSubview:volumeView];
查找并保存参考UISlider
:
__weak __typeof(self)weakSelf = self;
[[volumeView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[UISlider class]]) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
strongSelf.volumeSlider = obj;
*stop = YES;
}
}];
添加目标操作UIControlEventValueChanged
:
[self.volumeSlider addTarget:self action:@selector(handleVolumeChanged:) forControlEvents:UIControlEventValueChanged];
然后在音量更改时更新您的自定义控件(即通过硬件音量控件):
- (void)handleVolumeChanged:(id)sender
{
NSLog(@"%s - %f", __PRETTY_FUNCTION__, self.volumeSlider.value);
self.myCustomVolumeSliderView.value = self.volumeSlider.value;
}
还有其他方式:
- (IBAction)myCustomVolumeSliderViewValueChanged:(id)sender {
NSLog(@"set volume to: %f", self.myCustomVolumeSliderView.value);
self.volumeSlider.value = self.myCustomVolumeSliderView.value;
}
注意:确保设置self.volumeSlider.value
不会循环回到设置self.myCustomVolumeSliderView.value
。
希望这对某人有所帮助(并且 Apple 不会从 MPVolumeView 中删除 MPVolumeSlider)。