开发者

iPhone:How to manage UITextfield delegate methods on dynamic number of customcells

开发者 https://www.devze.com 2023-03-28 09:17 出处:网络
I have dynamic number of textfields in my tableview, I put each textfield into a customcell in IBand load the cells by nibName.

I have dynamic number of textfields in my tableview, I put each textfield into a customcell in IB and load the cells by nibName.

I want to validate and show alert as user ent开发者_如何学编程ers data, also when editingisDone I want to get the input value from user and save it to the relavent object.

for instance these are some delegate methods I can use:

- (void)textFieldDidEndEditing:(UITextField *)textField{
   //save the data
}

- (IBAction)textFieldDoneEditing:(id)sender {
    //hide the keypad when done is pressed
    [sender resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange{}

2 questions:

1-When getting user input and validating the input how will I know which textfield's delegate is fired since there are dynamic numbers of cells and textfields, and how can I manage this?

2-For hiding the keyboard I did this but not sure this is correct; -In IB I opened the customcell-->right click uitextfield and connect its didEndonExit to FirstResponder's textFieldDoneEditing method. This works but I can't return if I didnt add any chars to textfield. so it forces to write something in order to press the button.


With regards to your first question ...

In the following code I'll assume you have one UITextField in each cell. I'll also assume you've created an UITableViewCell subclass called CustomCell which contains an UITextField.

#pragma mark - UITableViewDataSource 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"CellIdentifier";
   CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (!cell)
   {
      cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault identifier:CellIdentifier] autorelease];
      cell.textField.tag = indexPath.row;
      cell.textField.delegate = self;
   }
   return cell; 
}

#pragma mark - UITextFieldDelegate 

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   NSLog(@"textField tag: %d", textField.tag); // this will show which textField did end editing ...
}


Regarding your second question; if I understand your problem correctly, unchecking "Auto-enable Return Key" in the textfield's properties in IB should allow you to press the return button even when it's empty. I tested this on a simple textfield in a UIView, but it should work in your case.

iPhone:How to manage UITextfield delegate methods on dynamic number of customcells

0

精彩评论

暂无评论...
验证码 换一张
取 消