UISlider平滑地改变价值

Ale*_*dro 7 cocoa-touch objective-c uislider ios

我有一个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];
}
Run Code Online (Sandbox Code Playgroud)

我想问三个问题.

1)为什么值变化的动画不起作用?2)为什么滑块位置只有在我从按钮上松开手指并且不跟随它时才会移动?3)使用NSTimer是最好的方法吗?我听说NSTimer耗费大量内存......

Dav*_*ist 16

为什么动画制作value不起作用

你显然找到了这个value属性.检查文档,你会看到这句话

要渲染从当前值到新值的动画过渡,您应该使用该setValue:animated:方法.

所以,正如文档所说的那样

[aSlider setValue:player.currentTime animated:YES];
Run Code Online (Sandbox Code Playgroud)

为什么只有在释放手指时才能获得事件

您松开手指时仅获得事件的原因是滑块不连续.从continuous物业的文件:

如果YES,滑块连续向相关目标的操作方法发送更新事件.如果NO,当用户释放滑块的拇指控件以设置最终值时,滑块仅发送动作事件.

NSTimer 不是最好的方式

不,使用NSTimer动画这样的变化绝对不是最好的方法,我会说使用计时器是非常糟糕的做法.它不仅无效且可能不精确,而且还失去了对动画缓动的内置支持.

如果你真的不能没有计时器,那么你应该至少使用一个CADisplayLink而不是一个NSTimer.它可以用于UI更新(与NSTimer不同).


B.S*_*.S. 5

你应该使用这些:

  1. 在创建滑块时将滑块属性设置continuousYES

    在你的情况下 aSlider.continuous = YES;

  2. 使用setValue:animated方法,

    在你的情况下 [aSlider setValue:player.currentTime animated:YES];