iOS开发之自定义弹出UIPickerView或UIDatePicker(动画效果)


前面iOS开发之UIPickerView控件的简单使用 (见 ) 用到的UIPickerView弹出来是通过 textField.inputView = selectPicker;   textField.inputAccessoryView = doneToolbar; 这中方法来做的。如果UIPickerView或UIDatePicker控件通过其他按钮或事件激活的时候怎么能像系统那样弹出来呢?为了实现这个需求,就要用到动画效果了。

1、新建一个Single View App项目,在.xib文件中添加控件如下:


两个button,一个UIDatePicker。

2、创建xib和ViewController的连接

按住Control键创建三个控件对于的映射。 创建后viewController.h代码如下
  1. #import <UIKit/UIKit.h>   
  2.   
  3. @interface ViewController : UIViewController  
  4. @property (retain, nonatomic) IBOutlet UIDatePicker *pickerView;  
  5. - (IBAction)popView:(id)sender;  
  6. - (IBAction)inView:(id)sender;  
  7. @property  (nonatomic, retain) NSString *string;  
  8. @end  

3、隐藏pickerView

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     self.pickerView.frame = CGRectMake(0, 480, 320, 260);  
  5. }  
把pickerView 放到屏幕以为下面。

4、弹出和弹回pickerView 在pickerView弹出来或回去的时候,设置动画
  1. - (IBAction)popView:(id)sender {  
  2.       
  3.     CGContextRef context = UIGraphicsGetCurrentContext();  
  4.     [UIView beginAnimations:nil context:context];  
  5.     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
  6.     [UIView setAnimationDuration:0.6];//动画时间长度,单位秒,浮点数   
  7.     [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];  
  8.     self.pickerView.frame = CGRectMake(0, 245, 320, 260);  
  9.       
  10.     [UIView setAnimationDelegate:self];  
  11.     // 动画完毕后调用animationFinished   
  12.     [UIView setAnimationDidStopSelector:@selector(animationFinished)];  
  13.     [UIView commitAnimations];  
  14. }  
  15.   
  16. - (IBAction)inView:(id)sender {  
  17.     CGContextRef context = UIGraphicsGetCurrentContext();  
  18.     [UIView beginAnimations:nil context:context];  
  19.     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
  20.     [UIView setAnimationDuration:0.6];//动画时间长度,单位秒,浮点数   
  21.     self.pickerView.frame = CGRectMake(0, 480, 320, 260);  
  22.       
  23.     [UIView setAnimationDelegate:self];  
  24.     // 动画完毕后调用animationFinished   
  25.     [UIView setAnimationDidStopSelector:@selector(animationFinished)];  
  26.     [UIView commitAnimations];  
  27. }  
  28. -(void)animationFinished{  
  29.     NSLog(@"动画结束!");  
  30. }  
动画结束后回调动画结束的函数。 运行,弹出   
第一个图片是弹出来到一半,第二个图片弹出全部。
  • 1
  • 2
  • 下一页

相关内容