我有一个 UIslider 设置 AVAdioRecording 的位置:
CGRect frame = CGRectMake(50.0, 230.0, 200.0, 10.0);
aSlider = [[UISlider alloc] initWithFrame:frame];
// Set a timer which keep getting the current music time and update the UISlider in 1 sec interval
sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
// Set the maximum value of the UISlider
aSlider.maximumValue = player.duration;
// Set the valueChanged target
[aSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventValueChanged];
[self.ViewA addSubview:aSlider];
- (void)updateSlider {
// Update the slider about the music time
[UIView beginAnimations:@"returnSliderToInitialValue" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:1.3];
aSlider.value = player.currentTime;
[UIView commitAnimations];
}
- (IBAction)sliderChanged:(UISlider *)sender {
// Fast skip the music when user scroll the UISlider
[player stop];
[player setCurrentTime:aSlider.value];
[player prepareToPlay];
[player play];
}
我想问三个问题。
1) 为什么值变化的动画不起作用? 2)为什么手指从按钮上松开 slider 位置才移动,不跟随移动? 3)使用 NSTimer 是最好的方法吗?我听说 NSTimer 很耗内存...
最佳答案
为什么动画值
不起作用
您显然找到了 value
属性。查看文档,你会看到这句话
To render an animated transition from the current value to the new value, you should use the
setValue:animated:
method instead.
所以,就像文档说的那样使用
[aSlider setValue:player.currentTime animated:YES];
为什么只有松开手指时才会收到事件
您仅在松开手指时才获得事件的原因是您的 slider 不连续。来自 continuous
属性的文档:
If
YES
, the slider sends update events continuously to the associated target’s action method. IfNO
, the slider only sends an action event when the user releases the slider’s thumb control to set the final value.
NSTimer 不是最好的方式
不,使用 NSTimer 像这样为变化设置动画绝对不是最好的方法,我会说使用计时器是非常糟糕的做法。它不仅无效而且可能不精确,而且您还会失去对缓动动画的内置支持。
如果你真的不能没有计时器,那么你至少应该使用 CADisplayLink
而不是 NSTimer
。它用于 UI 更新(与 NSTimer 不同,后者不是)。
关于ios - UISlider 平滑改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812907/