2017-05-13 12 views
0

通過類似的問題,tags基本上是所有人的答案。問題是我有一個自定義UITableViewCell其中有兩個文本字段的名字和姓氏。在我的應用程序中,我有一個+按鈕,單擊它時將新行添加到表視圖並重新加載表視圖。現在,如果用戶先前輸入了某個內容,然後單擊了按鈕,則會添加一個新行,但第一行中的名字和姓氏會消失。爲了解決這個問題,我採取了NSMutableArray,比如fNameArray,並且會添加用戶輸入的內容- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason這很好,但現在我必須爲姓創建另一個NSMutableArray,問題是我不知道如何識別文本字段上述代表。目前,我設置標籤cellForRowAtIndexPath作爲cell.tf_firstName.tag = indexPath.row; 除了標籤外,我如何識別UITextFiled

回答

0

tag財產,如果相同的標記值被分配到一個以上的文本字段相同的委託用於所有文本字段將無法正常工作。

下面是通過對每組文本字段使用不同的委託來解決此問題的實現。

TextFieldArrayManager管理一系列文本字段及其數據。它充當它管理的文本字段的代表。

@interface TextFieldArrayManager : NSObject <UITextFieldDelegate> 
@property NSMutableArray *textItems; 
@end 

@implementation TextFieldArrayManager 
- (void)textFieldDidEndEditing:(UITextField *)textField { 
    if (_textItems.count >= textField.tag + 1) { 
     if (textField.text) { 
      _textItems[textField.tag] = textField.text; 
     } 
     else { 
      _textItems[textField.tag] = @""; 
     } 
    } 
} 
@end 

視圖控制器使用單獨的TextFieldArrayManager來管理名和姓。

@interface ObjcTableViewController() 
@end 

@implementation ObjcTableViewController 

TextFieldArrayManager *firstNames; 
TextFieldArrayManager *lastNames; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    firstNames = [[TextFieldArrayManager alloc] init]; 
    firstNames.textItems = [NSMutableArray arrayWithObjects:@"George", @"Ludwig", @"Wolfgang", nil]; 

    lastNames = [[TextFieldArrayManager alloc] init]; 
    lastNames.textItems = [NSMutableArray arrayWithObjects:@"Handel", @"Beethoven", @"Mozart", nil]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return firstNames.textItems.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    ObjcTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    cell.firstName.delegate = firstNames; 
    cell.firstName.text = firstNames.textItems[indexPath.row]; 
    cell.firstName.tag = indexPath.row; 

    cell.lastName.delegate = lastNames; 
    cell.lastName.text = lastNames.textItems[indexPath.row]; 
    cell.lastName.tag = indexPath.row; 

    return cell; 
} 

要添加新的空行表中,你可以這樣做:

[firstNames.textItems addObject:@""]; 
[lastNames.textItems addObject:@""]; 
[self.tableView reloadData]; 

當用戶輸入文本,它將被保存到textItems。