Managing Delegate of UITextFields in Custom UITableViewCell

后端 未结 5 1559
长情又很酷
长情又很酷 2021-01-17 13:05

So I have looked around a quite a bit, and nothing on here seems to explain exactly the correct way of doing this. I have 7 UITextFields within a custom UITableViewCell.

5条回答
  •  一整个雨季
    2021-01-17 13:49

    You shouldn't have a problem setting the delegate of the cell's text field to be your view controller.

    This is what you need to do:

    1) The view controller needs to implement the UITextFieldDelegate protocol

    2) Declare a property for the text field in your custom cell

    @property (nonatomic, retain) IBOutlet UITextField *textField;
    

    3) Then set the view controller as the text field's delegate in the method cellForRowAtIndexPath

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"Cell";
    
        MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if (cell == nil) 
        {  
            // use this if you created your cell with IB
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0];   
    
            // otherwise use this  
            cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    
    
            // now set the view controller as the text field delegate  
            cell.textField.delegate = self;
        }
    
        // configure cell...
    
        return cell;
    }
    

提交回复
热议问题