2012-05-07 57 views
0

我要添加單元格上的UITextField。訪問UITextField在CellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:CellIdentifier]; 
} 


myLoc = [[UITextField alloc] initWithFrame:CGRectMake(35, 10, 250, 40)]; 
myLoc.adjustsFontSizeToFitWidth = YES; 
myLoc.textColor = [UIColor blackColor]; 
myLoc.textAlignment = UITextAlignmentCenter; 
myLoc.placeholder = @"Enter Location"; 
myLoc.returnKeyType = UIReturnKeyDone; 
myLoc.autocorrectionType = UITextAutocapitalizationTypeNone; 
myLoc.tag = indexPath.row; 
myLoc.delegate = self; 
[myLoc setEnabled:YES]; 
[cell addSubview:myLoc]; 

return cell; 
} 

並在textFieldShouldReturn我會寫從文本字段中一個可變的陣列中的NSUserDefaults的文本,並存儲。

-(BOOL)textFieldShouldReturn:(UITextField *)textField{ 

[myLoc resignFirstResponder]; 

[locationArray addObject:textField.text]; 
locName = [NSUserDefaults standardUserDefaults]; 
[locName setObject:locationArray forKey:@"textName"]; 
[locName synchronize]; 

NSLog(@"Done pressed %@",myLoc.text); 

return YES; 

}

...但myLoc.text總是空 任何想法我嗎?

回答

0

你的文本不應該是NULL,因爲它的NSString。你確定你在談論文本字段中的文字嗎?

添加NSLog時會輸出什麼(@%「@」,textField.text);你的shouldReturn方法?

您確定您在文本字段中輸入了?另外,即使沒有打字,你應該得到@「」而不是零。

+0

問題已解決myLoc = textField in textFieldShouldReturn – HugoBoss

+0

這不應該做任何事情,除非您調用myLoc的text屬性而不是在委託方法中給出的textField實例。那是你在做什麼? – RileyE

2

在委託方法中,請勿使用myLoc來引用textField,而是使用實際提供的textField指針作爲函數的參數。這實際上應該指向正確的文本字段,因此textField.text應該具有正確的值。

旁註:您在哪裏定義myLoc?它看起來像你試圖在你的viewcontroller上設置一個屬性。這樣你總是會覆蓋這個屬性。爲此,您根本不需要屬性,因此只需在功能範圍中本地定義myLoc,如UILabel *myLoc

+0

財產刪除:-) – HugoBoss

1

您最好創建自己的自定義UITableViewCell。你可以看到如何在這裏創建一個: tutorial

嘗試緊靠現有的UITableViewCell很難,最壞的情況是不可能的。你最好用定製單元格。

+1

歐文是正確的。有一個子類也會導致更簡潔的代碼和更好的可維護性。 –

+0

thx,我會試試! – HugoBoss

相關問題