2016-02-25 29 views
0

我試圖創建沒有故事板的UIDatePicker,並讓所選日期的UILabel顯示,但標籤顯示爲像堆積當在模擬器上選擇另一個日期時啓動。我以編程方式創建了UIDatePicker,並讓所選日期的UILabel顯示,但未能讓它正常顯示

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10,100,100)]; 
    [self.view addSubview:myLabel]; 

    UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, 10, 200, 200)]; 

    myPicker.datePickerMode = UIDatePickerModeDate; 

    [myPicker addTarget:self action:@selector(pickerChanged:) forControlEvents:UIControlEventValueChanged]; 

    [self.view addSubview:myPicker]; 
} 


- (void)pickerChanged:(id)sender 
{ 
    NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
    UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)]; 

    df.dateFormat = @"yyyy/MM/dd HH:mm"; 
    myLabel.text = [df stringFromDate:[sender date]]; 
    [self.view addSubview:myLabel]; 
} 

截圖如下: http://i.stack.imgur.com/VnJbD.png

我是初學者,無法找到解決方案。有人可以知道如何解決這個問題嗎?先謝謝你。

回答

2

這是因爲你每次創建新標籤更改日期

您需要重用的組件,在視圖中創建它確實負荷

- (void)viewDidLoad() { 
    .... 
    self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)]; 
    [self.view addSubview:self.myLabel]; 
} 

,那麼你可以只設置文本:

- (void)pickerChanged:(id)sender { 
    NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
    df.dateFormat = @"yyyy/MM/dd HH:mm"; 
    self.myLabel.text = [df stringFromDate:[sender date]]; 
} 
+0

它可以添加日期在您的標籤!非常感謝 –

0

先加標籤於viewDidLoad

UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)]; 
    [self.view addSubview:self.myLabel]; 

,然後在PickerChange

self.myLabel.text = [df stringFromDate:[sender date]]; 
+0

謝謝!它真的是炒作。 –

相關問題