2011-10-13 2 views
0

UITextField를 참조하는 데 문제가 있습니다. 지금은 참조를 확인하기 위해 UIAlertView를 사용하고 있습니다. 이 응용 프로그램에서 나는 매우 유사해야하고 HelperClass (나는 UIViewController를 서브 클래 싱하지 않아도 되는가?)를 만들 수있는 몇 가지 뷰가 있습니다. ViewItem은 Delegate 메시지를 TableItemsHelperClass에 전달하고 있습니다. 해당 TableItemsHelperClass 동적으로 테이블에 셀을 추가하고 있습니다. 이제 해당 셀을 참조하는 문제가 발생했습니다. 내 목표는 첫 번째 응답자 (키보드)를 릴리스하는 것이지만, 참조를 확인하기 위해 Textfields 콘텐츠를 가져 오는 것이 좋습니다.동적으로 UITableView에 추가 된 UITextField를 어떻게 참조합니까?


업데이트는 나는있는 UIViewController 서브 클래 싱하기 위해 HelperClass를 사용 다시 고려했다. 일부 변수 이름이 변경되었습니다. 이 두 가지 메소드는 모두 상위 클래스에서 찾을 수 있습니다. tableView:didSelectRowAtIndexPath:tableView:cellForRowAtIndexPath:이라면 is nil이 기록됩니다. 왜 내가 그 세포를 돌려주지 않는거야?

//tableView cellForRowAtIndexPath 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     NSString *CellIdentifier = [NSString stringWithFormat:@"Cell %d", indexPath.row]; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

     if (cell != nil) { 
      NSLog(@"is not nil"); 
      return cell; 
     } 

     NSLog(@"is nil"); 
     CGRect CellFrame  = CGRectMake(0, 0, 300, 65); 
     CGRect LabelViewFrame = CGRectMake(5, 5, 290, 25); 
     CGRect TextViewFrame = CGRectMake(5, 35, 290, 25); 

     cell = [[[UITableViewCell alloc] initWithFrame:CellFrame 
                   reuseIdentifier:CellIdentifier] autorelease]; 

     textFieldView = [[UITextField alloc] initWithFrame:TextViewFrame]; 
     labelView = [[UILabel alloc] initWithFrame:LabelViewFrame]; 
     textFieldView.backgroundColor = [UIColor greenColor]; 
     labelView.backgroundColor = [UIColor redColor]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 

     if (@"int" == [self.taxPayerTypes objectAtIndex:indexPath.row]) { 
      textFieldView.keyboardType = UIKeyboardTypeDecimalPad; 
     } 

     if (0 == indexPath.section) { 
      [labelView setText:[self.taxPayerList objectAtIndex:indexPath.row]]; 
     } else { 
      [labelView setText:[self.spouseList objectAtIndex:indexPath.row]]; 
     } 

     [cell.contentView addSubview:textFieldView]; 
     [cell.contentView addSubview:labelView]; 

    return cell; 
} 

//tableView didSelectRowAtIndexPath 
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    for(UIView *i in [[[self tableView:tableView cellForRowAtIndexPath:indexPath] contentView] subviews]) { 
     if ([i isKindOfClass:[UITextField class]]) { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSStringFromClass([i class]) 
                  message:[i text]//[(UITextField*)i text] 
                  delegate:self 
                cancelButtonTitle:@"a" 
                otherButtonTitles:@"b", nil]; 
      [alert show]; 
      [alert release]; 
     } 
    } 
} 

원래

//in the UIViewController///////////////////////////////////////////////////////////////////////////////// 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    return [TableItemsHelper tableView:tableView cellForRowAtIndexPath:indexPath]; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    for(UIView *i in [[[TableItemsHelper tableView:tableView cellForRowAtIndexPath:indexPath] contentView] subviews]) { 
     if ([i isKindOfClass:[UITextField class]]) { 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSStringFromClass([i class]) 
                  message:[i text] 
                  delegate:self 
                cancelButtonTitle:@"button 1" 
                otherButtonTitles: @"button", nil]; 

      [alert show]; 
      [alert release]; 

     } 
    } 
} 
//////////////////////////////////////////////////////////////////////////////////////////////////////// 


//In the TableItemsHelperClass////////////////////////////////////////////////////////////////////////// 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 
    CGRect CellFrame = CGRectMake(0, 0, 300, 65); 
    CGRect TextViewFrame = CGRectMake(5, 35, 290, 25); 

    // … 

    UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CellFrame 
                reuseIdentifier:CellIdentifier] autorelease]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
             reuseIdentifier:CellIdentifier] autorelease]; 
    } 


    UITextFieldView = [[UITextField alloc] initWithFrame:TextViewFrame]; 
    [cell.contentView addSubview:UITextFieldView]; 
    return cell; 
} 

//////////////////////////////////////////////////////////////////////////////////////////////////////// 
+0

정확하게'resignFirstResponder' 메서드를 호출 할 예정입니까? –

+0

기존 버튼을 사용하여 기존 NavigationRightBarButton을 전환 할 수 있다고 생각하거나 사용자가 텍스트 필드 외부를 누를 때 호출 할 수 있다고 생각했습니다. 이 필드의 대부분은 텍스트이고 십진수를 가질 확률이 높으므로 키보드의 완료 버튼이 작동하지 않습니다. – TMB

+0

업데이트 : 상위 클래스로 도우미 클래스에서 마이그레이션했습니다. – TMB

답변

1

나는 당신이 당신의 UIViewController를 서브 클래스로되어 있지 않은 인상을 왜 모르겠어요. 사실 모든 뷰 컨트롤러는 UIViewController의 하위 클래스이며, 거의 동일한 여러 개의 뷰 컨트롤러가있는 경우 사용자가 만든 다른 뷰 컨트롤러에서 하위 클래스로 분류하면 도움이 될 수 있습니다. 그러나 이는 사용자의 질문과 관련이없는 것 같습니다.

사용자 지정 셀을 만들기 위해 UITableViewCell의 하위 클래스를 만들면 수행하는 것처럼 보이기 쉽습니다. 그런 다음 "UITextFieldView"는 서브 클래 싱 된 셀의 속성이 될 수 있으므로 테스트 루프를 사용하여 해당 클래스 유형의 하위 뷰를 찾는 대신 직접 액세스 할 수 있습니다.

(변수 이름 지정은 일반적인 규칙을 따르지 않으므로 코드를 읽기가 어려울 수 있습니다. "UITextFieldView"보다는 "textFieldView"와 같은 변수 이름을 사용하는 것이 좋습니다. 후자는 일반적인 클래스 이름처럼 보입니다.)

"도우미 클래스"는 UITableViewCell의 하위 클래스로 바꿀 수 있습니다. UITableViewCell을 서브 클래 싱하는 몇 가지 예제가 있습니다. 참고 자료가 필요하면 알려주세요. 링크를 게시 할 것입니다. (컴퓨터 앞에 앉아서 작업 할 수 있습니다.)

다른 도움이되기를 바랍니다. 나는 의견을 냈다. cellForRowAtIndexPath에서

+0

편집자 코멘트는 훌륭하고 환영합니다. – TMB

0

didSelectRowAtIndexPath에서
// use local variable, not instance variable 
UITextField *textField = [[UITextField alloc] initWithFrame:TextViewFrame]; 
// tag it for later access 
textField.tag = 1; 
[cell.contentView addSubview:textField]; 
[textField release]; 

// NOT [TableItemsHelper tableView:cellForRowAtIndexPath:] 
// that would give you a new cell 
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
UITextField *textField = [cell viewWithTag:1]; 
// do what you want with textField 

"나는이있는 UIViewController 서브 클래스로되어 있지 않다?"

아니요. 사실이 아닙니다. 사실 그것은 코드가 UIViewController를 상속하는 것처럼 보입니다.하지만 어쩌면 당신은 당신이처럼의 UIViewController의 하위 클래스를 서브 클래 싱 안 생각 의미 : 몰라요

@interface MyViewController : UIViewController 
@interface MyViewControllerFirstVariant : MyViewController 
@interface MyViewControllerSecondVariant : MyViewController 

, 당신이 원한다면 그렇게 할 수 있다고 생각합니다. 하지만 헬퍼 클래스를 사용하는 디자인 패턴이 더 깨끗하다고 ​​생각합니다.

관련 문제