iOS開發10:UIDatePicker控件

UIDatePicker是一個能夠用來選擇或者設置日期的控件,不過它是像轉輪同樣的控件,並且是蘋果專門爲日曆作好的控件,以下圖所示:ide

除了UIDatePicker控件,還有一種更通用的轉輪形的控件:UIPickerView,只不過UIDatePicker控件顯示的就是日曆,而UIPickerView控件中顯示的內容須要咱們本身用代碼設置。本篇文章簡單介紹UIDatePicker控件,後邊的文章會介紹UIPickerView。ui

一、運行Xcode 4.2,新建一個Single View Application,名稱爲UIDatePicker Test,其餘設置以下圖所示:code

二、單擊ViewController.xib,打開Interface Builder。拖一個UIDatePicker控件到視圖上:orm

三、而後拖一個按鈕在視圖上,並修改按鈕名稱爲Select:事件

單擊按鈕後,彈出一個Alert,用於顯示用戶所做選擇。string

四、建立映射:打開Assistant Editor,選中UIDatePicker控件,按住Control,拖到ViewController.h中:it

新建一個Outlet,名稱爲datePicker:io

而後以一樣的方式爲按鈕創建一個Action映射,名稱爲buttonPressed,事件類型爲默認的Touch Up Inside。class

五、選中UIDatePicker控件,打開Attribute Inspector,在其中設置Maximum Date爲2100-12-31:sed

六、單擊ViewController.m,找到buttonPressed方法,在其中添加代碼以下:

- (IBAction)buttonPressed:(id)sender {
    NSDate *selected = [datePicker date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm +0800"];
    NSString *destDateString = [dateFormatter stringFromDate:selected];
    
    NSString *message = [[NSString alloc] initWithFormat: 
                         @"The date and time you selected is: %@", destDateString]; 
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle:@"Date and Time Selected" 
                          message:message
                          delegate:nil 
                          cancelButtonTitle:@"Yes, I did." 
                          otherButtonTitles:nil]; 
    [alert show]; 
}

其中NSDate *selected = [datePicker date];用於得到UIDatePicker所選擇的日期和時間,後邊的三行代碼把日期和時間改爲東八區的時間格式。

找到viewDidLoad方法,添加代碼以下:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    NSDate *now = [NSDate date];
    [datePicker setDate:now animated:NO]; 
}

找到viewDidUnload方法,添加代碼:

- (void)viewDidUnload
{
    [self setDatePicker:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.datePicker = nil;
}

七、如今運行,顯示以下圖所示:

 

相關文章
相關標籤/搜索