2010-12-07 4 views
12

UITextField가 포함 된 IB에서 만든 UITableViewCell (연결된 UITableViewCell 하위 클래스 포함, .m & .h)이 있습니다. 이 UITextField는 UITableViewCell 하위 클래스의 IBOutlet에 연결되며 속성도 갖습니다. 의 UITextField를사용자 지정 UITableViewCell에서 UITextField에 액세스

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textfieldTableCell"]; 
    if (cell == nil) { 
     // Create a temporary UIViewController to instantiate the custom cell. 
     UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"TextfieldTableCell" bundle:nil]; 
     // Grab a pointer to the custom cell. 
     cell = (TextfieldTableCell *)temporaryController.view; 
     // Release the temporary UIViewController. 
     [temporaryController release]; 
    } 

    return cell; 

} 

UITextField에 잘 표시하고 키보드가 예상대로 클릭하면 팝업,하지만 난에 액세스 어떻게 (는 .text 속성을 가져) : 내 테이블 뷰 컨트롤러에서 나는 다음과 같은 코드를 사용하여이 사용자 정의 셀을 사용하고 있습니다 각 행에는? 또한 어떻게 UITextFields의 'textFieldShouldReturn'메서드를 처리합니까?

cellForRowAtIndexPath에서

답변

21

나는 무엇 영업 이익은 이해하려고하는 것은 사용자가 각 필드에 데이터를 입력 한 일단의 UITextField 값에 액세스하는 방법을 생각합니다. @willcodejavaforfood가 제안한대로 셀을 만들 때 사용할 수 없습니다.

저는 양식을 구현하여 가능한 한 사용자 편의를 도모하려고 노력했습니다. 그것은 가능하지만 당신이 가지고있는 UITableViewCells/UITextFields의 수에 따라 꽤 복잡하게 될 수 있다는 것을 알아 두십시오. 귀하의 질문에 다시에 첫째

:의 UITextField의 값을 액세스하는 : 나는도를 사용

- (void) textFieldDidEndEditing:(UITextField *)textField { 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(CustomCell*)[[textField superview] superview]]; // this should return you your current indexPath 

     // From here on you can (switch) your indexPath.section or indexPath.row 
     // as appropriate to get the textValue and assign it to a variable, for instance: 
    if (indexPath.section == kMandatorySection) { 
     if (indexPath.row == kEmailField) self.emailFieldValue = textField.text; 
     if (indexPath.row == kPasswordField) self.passwordFieldValue = textField.text; 
     if (indexPath.row == kPasswordConfirmField) self.passwordConfirmFieldValue = textField.text; 
    } 
    else if (indexPath.section == kOptionalSection) { 
     if (indexPath.row == kFirstNameField) self.firstNameFieldValue = textField.text; 
     if (indexPath.row == kLastNameField) self.lastNameFieldValue = textField.text; 
     if (indexPath.row == kPostcodeField) self.postcodeFieldValue = textField.text; 
    } 
} 

:

1) 뷰 컨트롤러가 <UITextFieldDelegate>

2) 다음과 같은 메소드를 구현합니다 비슷한 구문으로 현재 수정 된 입력란이 표시되는지 확인하십시오.

- (void) textFieldDidBeginEditing:(UITextField *)textField { 
    CustomCell *cell = (CustomCell*) [[textField superview] superview]; 
    [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; 
} 
,210

그리고 마지막으로, 당신은 비슷한 방법으로 textViewShouldReturn:을 처리 할 수 ​​

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(CustomCell*)[[textField superview] superview]]; 
    switch (indexPath.section) { 
     case kMandatorySection: 
     { 
      // I am testing to see if this is NOT the last field of my first section 
      // If not, find the next UITextField and make it firstResponder if the user 
      // presses ENTER on the keyboard 
      if (indexPath.row < kPasswordConfirmField) { 
       NSIndexPath *sibling = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:indexPath.section]; 
       CustomCell *cell = (CustomCell*)[self.tableView cellForRowAtIndexPath:sibling]; 
       [cell.cellTextField becomeFirstResponder]; 
      } else { 
       // In case this is my last section row, when the user presses ENTER, 
       // I move the focus to the first row in next section 
       NSIndexPath *sibling = [NSIndexPath indexPathForRow:kFirstNameField inSection:kOptionalSection]; 
       MemberLoginCell *cell = (MemberLoginCell*)[self.memberTableView cellForRowAtIndexPath:sibling]; 
       [cell.cellTextField becomeFirstResponder]; 
      } 
      break; 
     }   
     ... 
} 
+0

건배 Rog, 내 Mac으로 돌아 가면 그걸 시험해 보겠습니다. 나는 애플이 어떻게하는지 궁금해하는데, 셋팅 앱처럼 나는 이것보다 조금 더 똑바로/더 깨끗하게 될 줄 알았다. 아마 그들은 완전히 다른 방식으로 코드를 작성했을 것입니다. – Darthtong

8

:이 코드

yourTextField.tag=indexPath.row+1; //(tag must be a non zero number) 

그런 다음 당신이 당신의 정의 셀 당신이 그것을에 반대하는 조언을 줄위한 클래스를 생성 한 경우

UITextField *tf=(UITextField *)[yourView viewWithTag:tag]; 
0

를 사용하여 텍스트 필드에 액세스를 포함한다.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    MyCustomCell* cell = (MyCustomCell *) [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"]; 
    if (cell == nil) { 
     // Load the top-level objects from the custom cell XIB. 
     NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil]; 
     // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain). 
     cell = (MyCustomCell *) [topLevelObjects objectAtIndex:0]; 
    } 

    // This is where you can access the properties of your custom class 
    cell.myCustomLabel.text = @"customText"; 
    return cell; 
} 
2

가 더욱 모두 문제를 해결하는 간단한 방법, 셀에 대한

1.Create 사용자 정의

있는 UITableViewCell 클래스 (egtextfieldcell)

2.Now의 textfieldcell.h 파일 호출 textFieldDelegate textfieldcell 3.In

인치

-(BOOL)textFieldShouldReturn:(UITextField *)textField    
{   
     [self.mytextBox resignFirstResponder];   
     return YES;   
} 

5 (두 번째 문제) 지금의 m 파일 쓰기 textFieldDelegate 방법 즉

-(BOOL)textFieldShouldReturn:(UITextField *)textField; 

-(void)textFieldDidEndEditing:(UITextField *)textField; 
  1. (제 1 과제),

    -(void)textFieldDidEndEditing:(UITextField *)textField 
    { 
        nameTextField = mytextBox.text; 
    } 
    

    6.c 대리인 방법의 구현 쓰기 MaintableViewController에

    -(void)textName:(NSString *)name{ 
        Nametext = name; 
        NSLog(@"name = %@",name); 
    } 
    

    8.call 셀 클래스 위임 방법

    @protocol textFieldDelegate <NSObject> 
    -(void)textName:(NSString *)name; 
    @end 
    

    7.In MaintableViewController.m 파일을 지정 위임 방법 reate 및 전달 didendmethod

    9.now의 변수는, jQuery과 셀을 초기화

    10.thats을 cell.delegate 위해 자기를 할당 변수를 텍스트 필드에서 기본보기로 전달한 다음, 이제 변수로 원하는 것은 무엇이든 할 수 있습니다.

0

This 자습서가 도움이되었습니다. 태그를 통해 필요한 객체를 참조 할 수 있습니다. 에 스토리 보드 드래그

UIImageView 또는 UITextField 등 그것을 참조하는 태그를 사용하여 다음 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath에서 (당신이 원하는 무엇이든) 100 태그를 설정합니다. 이것은 내가 스위프트에 내 사용자 정의 UITableViewCell 내부의 UITextField 내부의 텍스트를 얻을 수 있었다 어떻게

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

// Configure the cell... 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

UITextField *tField = (UITextField *)[cell viewWithTag:100]; 

return cell; 
} 
0

: 여기

는 그냥 스토리 보드에 태그를 설정하는 것을 기억 할 수있는 일입니다. 내 UIButton 안에 내 에 @IBAction이있는 또 다른 사용자 정의 UITableViewCell 내부에서 액세스했습니다. 내 UITableViewController에 섹션이 하나만 있지만 어쨌든 쉽게 설정하고 할당 할 수 있으므로 중요하지 않습니다. 내 UIButton를 도청 할 때마다

@IBAction func submitButtonTapped(sender: UIButton) { 
    print("Submit button tapped") 

    let usernameCell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! UsernameTableViewCell 
    print("Username: \(usernameCell.usernameTextField.text)") 
} 

, 그것은 나에게 내 UITextField 내부의 텍스트의 업데이트 된 값을 제공합니다.

관련 문제