我正在使用UIPickerView来显示随机数.用户可以按下按钮,从而触发随机选择UIPickerView内的数字.
当我调用方法时,UIPickerView中显示的对象或数字有多少并不重要:
[self.picker selectRow:randomRow inComponent:0 animated:YES];
它总是以相同的时间间隔进行动画处理.
我试过把它放在一个动画块中:
[UIView beginAnimations:@"identifier" context:nil]; // code [UIView commitAnimations];
但这似乎是一个死路一条.
我也尝试在完成块中执行它:
// 0.34f is the approximate defualt apple animation [UIView animateWithDuration:0.34f animations:^{ [self.picker selectRow:randomRow inComponent:0 animated:YES]; } completion:^(BOOL finished) { [UIView animateWithDuration:0.34f animations:^{ [self.picker selectRow:randomRow inComponent:0 animated:YES]; } completion:nil]; }];
任何帮助,将不胜感激.
解决方法
我做了一个项目并玩了一段时间,直到找到这个棘手的解决方案.它基于performSelector方法:afterDelay
以下是按钮的内部代码:
- (void)click:(id)sender { int randomRow = <>;//Your random method int currentRow = [_picker selectedRowInComponent:0]; int i = 0; while(1) { i++; NSString *rowToSelectString = [NSString stringWithFormat:@"%d",currentRow]; NSDictionary *rowToSelectDictionary = @{@"row":rowToSelectString}; if(randomRow < currentRow) { // Go backward currentRow--; } else { // Go forward currentRow++; } [self performSelector:@selector(selectRowInPicker:) withObject:rowToSelectDictionary afterDelay:i*0.1];//Change the delay as you want if(currentRow == randomRow) { break; } } }
诀窍:
-(void)selectRowInPicker:(NSDictionary *)rowToSelectDictionary { NSInteger row = [[rowToSelectDictionary objectForKey:@"row"] integerValue]; [_picker selectRow:row inComponent:0 animated:YES]; }
这对我很有用.告诉我你是否遇到问题.