Search code examples
iphoneiosios5uitableviewios4

UITextField in UITableViewCell


I want to place UItextField in UITableViewCell but I have problem. Text field don't appear. This is my code:

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString         *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 120.0f, 45.0f)];
        self.textField.textColor = [UIColor blackColor];

        [self.contentView addSubview:self.textField];
    }

    return self;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    TextFieldCell *cell = (TextFieldCell*)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    switch (indexPath.row) {
        case 1:
            cell.textField.placeholder = @"Username";
            break;
        case 2:
            cell.textField.placeholder = @"Password";
            break;
        case 3:
            cell.textField.placeholder = @"Server Address";
            break;
        case 4:
            cell.textField.placeholder = @"Description";
            break;            
        default:
            break;
    }

    return cell;
}

I test and initWithStyle method is called.Can someone help me?


Solution

  • IF you have .xib file for TextFieldCell then drag and drop textview and set all properties form Interface builder else you can create only *.XIB to use as TableViewCell by*

    In .h file

    IBOutlet UITableViewCell* CUSTOM_CELL_XIB;

    In .m file in cellForRowAtIndexPath method

    static NSString *CellIdentifier = @"Cell";
    
    
    UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) 
    {
        [[NSBundle mainBundle] loadNibNamed:@"CUSTOM_CELL_XIB" owner:self options:nil]; 
        cell = CUSTOM_CELL_XIB;
    }
    

    and directly drag and drop textField or whatever UI you want, I think it is efficient way for custom cell creation.

    This will perfectly work