UITableViewCell with UITextField losing the ability to select UITableView row?

前端 未结 5 771
萌比男神i
萌比男神i 2020-12-15 07:44

I am almost done implementing a UITableViewCell with a UITextField in it. Rather then going through CGRectMake and UITableViewCe

5条回答
  •  一整个雨季
    2020-12-15 08:31

    First of all you needed to use reuseIdentifier for cellForRowAtIndexPath, reason if you do not use reuseIdentifier is: when you scroll up and down, it will always allocate new cell and new textfields so you need to put cell==nil condition, so revised code is here:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      static NSString *reuseIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease];
    
         UITextField *amountField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 190, 30)];
         amountField.placeholder = @"Enter amount";
         amountField.keyboardType = UIKeyboardTypeDecimalPad;
         amountField.textAlignment = UITextAlignmentRight;
         amountField.clearButtonMode = UITextFieldViewModeNever; 
         [amountField setDelegate:self];
         [cell.contentView addSubview:amountField];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [[cell textLabel] setText:@"Amount"];
    
    return cell;
    }
    

    In didSelect delegate method you can do like this

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
      [prevField resignFirstResponder];
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      UIView *view = [[cell.contentView subviews] lastObject];
      if([view isKindOfClass:[UITextField class]]{
         currentField = (UITextField*)view;
      }
      [currentField becomeFirstResponder];
      prevField = currentField;
    }
    

提交回复
热议问题