当selectRow动画完成后,如何从UIPickerView获得回调?

时间:2009-03-31 22:15:13

标签: iphone uipickerview

我有一个UIPickerView,我想在selectRow动画完成时收到通知。

我在我的视图控制器中尝试了以下方法,该控制器具有对UIPickerView的引用,但它不起作用:

-(void)viewDidLoad
{
    ...
    [UIPickerView setAnimationDelegate:self];
    [UIPickerView setAnimationDidStopSelector:@selector(animationFin ished:finished:context];
    ...
}

- (void)animationFinishedNSString *)animationID finishedBOOL)finished contextvoid *)context
{
    if (finished) {

    }

}

然后在我的代码中的某处,我启动动画:

[picker selectRow:random() % pickerDataCount inComponent:0 animated:YES];

3 个答案:

答案 0 :(得分:2)

您需要将方法调用嵌套到beginAnimations / commitAnimation块中。

- (void) animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context {
    NSLog(@"Here I am");
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    [UIView beginAnimations:@"1" context:nil]; // nil = dummy
    [UIPickerView setAnimationDelegate:self];
    [UIPickerView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
    [myPickerView selectRow:0 inComponent:0 animated:YES]; // jump with any swipe in picker always to row=0 as dummy to initiate animation
    [UIView commitAnimations];

    //...whatever comes in addition...
}

答案 1 :(得分:1)

您可以从viewForRow向自己发布通知 当它要求查看组件和&你感兴趣的那一行。

你只需要保持行&组件作为属性 并在调用selectRow之前设置它们。而且,在viewForRow

if((component == [self component]&&(row == [self row])   向自己发布通知

答案 2 :(得分:1)

我用这里提到的不同答案混合解决了它。行为将是等待滚动完成然后保存所选值。

  1. 创建两个变量,用于存储滚动状态和应保存状态。在didSet中,如果在选择器滚动时按下了保存按钮,您将检查。如果是,请在选择器完成滚动后调用save。

    var shouldSave = false
    var pickerViewIsScrolling = false {
        didSet {
            if !pickerViewIsScrolling && shouldSave {
                save()
            }
        }
    }
    
  2. 要识别选择器是否正在滚动,请在选择器的pickerViewIsScrolling = true方法中添加viewForRow

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        pickerViewIsScrolling = true
        ...
    }
    
  3. 要识别选择器是否已停止滚动,请将pickerViewIsScrolling = false添加到选择器的didSelectRow

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
         pickerViewIsScrolling = false 
         ...
    }
    
  4. save()函数中添加以下内容以检查选择器是否滚动(并在停止后保存)或者不滚动并直接保存。

    func save() {
         if(pickerViewIsScrolling){
              shouldSave = true
              return
         }
    
         // Save the Data...
    
    }
    
  5. 最后在此行添加viewDidAppear函数以捕获初始生成视图的pickerViewIsScrolling = true

    override func viewDidAppear(_ animated: Bool) {
    
         super.viewDidAppear(animated)
    
         pickerViewIsScrolling = false
    
         ...
    
    }
    
  6. 这对我来说很好。我还在按下保存时实现了按钮的停用,它正在等待滚动完成。因此,在滚动停止之前,用户不会为什么没有发生任何事情而感到困惑。