此範例為一個日期選擇的應用,

點擊button後,觸發datePciker並顯示於label上。

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *myDatePicker;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
- (IBAction)toEnter:(id)sender;
- (IBAction)datePickerChanged:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)toEnter:(id)sender {
    
    if( _myDatePicker.hidden == YES){ //若datePciker為隱藏則將它開啟
        [_myDatePicker setHidden:NO];
    }else{
        [_myDatePicker setHidden:YES];
    }
}

- (IBAction)datePickerChanged:(id)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"]; //設定date顯示格式
    NSString *dateString = [dateFormatter stringFromDate:[_myDatePicker date]]; //轉為字串格式
    _dateLabel.text = dateString;
}

@end

 

arrow
arrow
    文章標籤
    UIDatePicker
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()