此範例為一個日期選擇的應用,
點擊button後,觸發datePciker並顯示於label上,
將UIDatePicker調整到使用者的生日,
計算年齡後並印在Label。
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIDatePicker *myDatePicker;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
- (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){
[_myDatePicker setHidden:NO];
}else{
[_myDatePicker setHidden:YES];
}
}
- (IBAction)datePickerChanged:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"YYYY/MM/dd"];
NSString *dateString = [dateFormatter stringFromDate:[_myDatePicker date]];
_dateLabel.text = dateString;
NSDate *now =[NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear fromDate:[_myDatePicker date] toDate:now options:0];
NSInteger age = [ageComponents year];
_ageLabel.text = [NSString stringWithFormat:@"%ld", (long)age];
}
@end
文章標籤
全站熱搜
留言列表