hachinoBlog

hachinobuのエンジニアライフ

tableViewCell上にUISliderを載せてアニメーションしたらおかしくなる件

事象

カスタムのUITableViewCell上にUISliderをaddしてcellforRowで読み込まれると同時にSliderをアニメーションしてみたのだけれど、minimumTrackTintColorとmaximumTrackTintColor割合がおかしく、明らかに変なアニメーションをしだした。

解決方法

Sliderのアニメーションをdispatch_afterで遅らせてやるとうまくいった。

ちなみに[UIView animateKeyframesWithDuration...のdelay:をセットしてもダメだった。

下記サンプルではtag10にUISliderが紐付けられているものとする。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UISlider *slider = (UISlider *)[cell viewWithTag:10];
        slider.value = 0;
        [UIView animateKeyframesWithDuration:1 delay:0 options:UIViewKeyframeAnimationOptionAllowUserInteraction animations:^{
            [slider setValue:0.8 animated:YES];
        } completion:^(BOOL finished) {
            
        }];
    });
    
    return cell;
}

うまくいかない時は遅延処理させると解決するのは結構あるけど、 delayじゃなくdispatch_after使わないとダメだったとは。。

かなりの時間を使ってしまったので久しぶりにメモ。