歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS開發之自定義彈出UIPickerView或UIDatePicker(動畫效果)

iOS開發之自定義彈出UIPickerView或UIDatePicker(動畫效果)

日期:2017/3/1 10:13:25   编辑:Linux編程

前面iOS開發之UIPickerView控件的簡單使用 (見 http://www.linuxidc.com/Linux/2012-08/67784.htm) 用到的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. @interface ViewController : UIViewController
  3. @property (retain, nonatomic) IBOutlet UIDatePicker *pickerView;
  4. - (IBAction)popView:(id)sender;
  5. - (IBAction)inView:(id)sender;
  6. @property (nonatomic, retain) NSString *string;
  7. @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. CGContextRef context = UIGraphicsGetCurrentContext();
  3. [UIView beginAnimations:nil context:context];
  4. [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  5. [UIView setAnimationDuration:0.6];//動畫時間長度,單位秒,浮點數
  6. [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
  7. self.pickerView.frame = CGRectMake(0, 245, 320, 260);
  8. [UIView setAnimationDelegate:self];
  9. // 動畫完畢後調用animationFinished
  10. [UIView setAnimationDidStopSelector:@selector(animationFinished)];
  11. [UIView commitAnimations];
  12. }
  13. - (IBAction)inView:(id)sender {
  14. CGContextRef context = UIGraphicsGetCurrentContext();
  15. [UIView beginAnimations:nil context:context];
  16. [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  17. [UIView setAnimationDuration:0.6];//動畫時間長度,單位秒,浮點數
  18. self.pickerView.frame = CGRectMake(0, 480, 320, 260);
  19. [UIView setAnimationDelegate:self];
  20. // 動畫完畢後調用animationFinished
  21. [UIView setAnimationDidStopSelector:@selector(animationFinished)];
  22. [UIView commitAnimations];
  23. }
  24. -(void)animationFinished{
  25. NSLog(@"動畫結束!");
  26. }
動畫結束後回調動畫結束的函數。 運行,彈出
第一個圖片是彈出來到一半,第二個圖片彈出全部。
Copyright © Linux教程網 All Rights Reserved