前面iOS开发之UIPickerView控件的简单使用 (见 ) 用到的UIPickerView弹出来是通过 textField.inputView = selectPicker; textField.inputAccessoryView = doneToolbar; 这中方法来做的。如果UIPickerView或UIDatePicker控件通过其他按钮或事件激活的时候怎么能像系统那样弹出来呢?为了实现这个需求,就要用到动画效果了。
1、新建一个Single View App项目,在.xib文件中添加控件如下:两个button,一个UIDatePicker。
2、创建xib和ViewController的连接按住Control键创建三个控件对于的映射。
创建后viewController.h代码如下
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (retain, nonatomic) IBOutlet UIDatePicker *pickerView; - (IBAction)popView:(id)sender; - (IBAction)inView:(id)sender; @property (nonatomic, retain) NSString *string; @end
3、隐藏pickerView
- (void)viewDidLoad { [super viewDidLoad]; self.pickerView.frame = CGRectMake(0, 480, 320, 260); }
把pickerView 放到屏幕以为下面。 4、弹出和弹回pickerView在pickerView弹出来或回去的时候,设置动画
- (IBAction)popView:(id)sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.6];//动画时间长度,单位秒,浮点数 [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; self.pickerView.frame = CGRectMake(0, 245, 320, 260); [UIView setAnimationDelegate:self]; // 动画完毕后调用animationFinished [UIView setAnimationDidStopSelector:@selector(animationFinished)]; [UIView commitAnimations]; } - (IBAction)inView:(id)sender { CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:0.6];//动画时间长度,单位秒,浮点数 self.pickerView.frame = CGRectMake(0, 480, 320, 260); [UIView setAnimationDelegate:self]; // 动画完毕后调用animationFinished [UIView setAnimationDidStopSelector:@selector(animationFinished)]; [UIView commitAnimations]; } -(void)animationFinished{ NSLog(@"动画结束!"); }
动画结束后回调动画结束的函数。运行,弹出