2011-07-26 20 views
0

我對UITextField有以下代碼。我遇到的問題是文本不會持續。例如,當我呈現模態視圖時,請將其解除,UITextField不再包含文本。我希望文字留在那裏,直到我用文本字段減少視圖。在使用UITextField和NSString時遇到問題

我顯示UITextField這樣的:

UITextField *nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)]; 
nameTextField.delegate = self; 
[nameTextField addTarget:self action:@selector(editingEnded) forControlEvents:UIControlEventEditingDidEnd]; 
[nameTextField setEnabled: YES]; 
self.myTextField = nameTextField; 
[nameTextField release]; 

然後,我有:

- (void)editingEnded 
{ 
    NSString *tempRoutineName = self.myTextField.text; 
    self.routineName = tempRoutineName; 
    [tempRoutineName release]; 
} 

回答

3

相反editingEnded的,實行UITextFieldDelegate協議。轉到textFieldDidEndEditing方法並重新分配文本的值。

一樣,

-(void) textFieldDidEndEditing:(UITextField *)textField{ 

if (textField.tag ==0){ 
    self.myTextField = textField; 

    // myTextField is a property 
    } 

現在在在viewDidLoad方法或viewWillAppear方法,繼續分配該值迴文本框。

必要時使用[tableView reloadData]如果在tableView中使用或使用[self reloadInputViews](如有必要)。

然後,它的所有邏輯。代碼中沒有太複雜的內容。

+0

我發佈的第一塊代碼實際上是在configureCell方法中,因爲UITextField位於UITableViewCell中,所以我仍然應該在viewDidLoad中進行操作,或者在此方法中執行操作? – Jon

+0

沒有。在'cellForRowAtIndexPath'方法中,初始化文本字段。 – Legolas

+0

我不能'self.myTextField = textField',因爲'textField是在'configureCell'方法中聲明的。 – Jon

0

使用UITextFieldDelegate方法是textFieldDidEndEditing,當編輯結束

0

在我看來它被調用:

NSString *tempRoutineName = self.myTextField.text; 
self.routineName = tempRoutineName; 
[tempRoutineName release]; 

你還沒有自己tempRoutineName釋放。評論釋放並檢查。