在自定义UITableViewCell中访问UITextField

时间:2010-12-07 10:09:20

标签: iphone objective-c ios uitableview

我在IB中创建了一个包含UITextField的UITableViewCell(带有关联的UITableViewCell子类,.m& .h)。此UITextField连接到UITableViewCell子类中的IBOutlet,并且还具有属性。在我的表视图控制器中,我使用此自定义单元格,其代码如下:

// 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属性)每行包含的UITextField?以及如何处理UITextFields的'textFieldShouldReturn'方法?

6 个答案:

答案 0 :(得分:21)

我认为OP试图理解的是,一旦用户在每个字段中输入数据,如何访问UITextField值。根据@willcodejavaforfood的建议,在创建单元格时不可用。

我一直在实施一个表单并尝试尽可能地使用它。这是可行的,但请注意,根据您拥有的UITableViewCells / UITextField的数量,它可能会变得非常复杂。

首先回答你的问题:访问UITextField的值:

1)使您的视图控制器成为<UITextFieldDelegate>

2)实施以下方法:

- (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;
    }   
}

我也使用类似的语法来确保当前编辑的字段可见:

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

最后,你可以用类似的方式处理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;
        }           
        ...
}

答案 1 :(得分:8)

在cellForRowAtIndexPath中:包含此代码,

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

然后使用

访问textField
UITextField *tf=(UITextField *)[yourView viewWithTag:tag];

答案 2 :(得分:2)

解决这两个问题还有更简单的方法,

1.为单元格创建自定义uitableviewCell类(例如,textfieldcell)

2.现在,在textfieldcell.h文件中调用textFieldDelegate

3.在textfieldcell.m文件中编写textFieldDelegate方法  即

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

-(void)textFieldDidEndEditing:(UITextField *)textField;
  1. (第一个问题)现在,在
  2.  -(BOOL)textFieldShouldReturn:(UITextField *)textField             
     {          
          [self.mytextBox resignFirstResponder];           
          return YES;        
     }
    

    5.(第二个问题),

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

    6.在MaintableViewController

    中创建自定义委托方法
    @protocol textFieldDelegate <NSObject>
    -(void)textName:(NSString *)name;
     @end
    

    7.在MaintableViewController.m文件中编写委托方法的实现,

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

    8.在单元格类中调用委托方法,并在didendmethod中传递变量

    9.现在,在uitableview

    中初始化单元格时,将self指定给cell.delegate

    10.你将变量从文本字段传递到主视图。现在用变量做任何你想要的事情

答案 3 :(得分: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;
}

答案 4 :(得分:0)

This教程对我很有帮助。您可以通过标记引用所需的任何对象。

在故事板中拖动UIImageViewUITextField等并将标记设置为100(无论您想要什么),然后在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中使用标记引用它。

这是你可以做的事情,只需记住在故事板中设置标签:

 - (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;
 }

答案 5 :(得分:0)

这就是我设法在Swift中的自定义UITextField内的UITableViewCell内获取文本的方法。我在UIButton内的另一个自定义UITableViewCell@IBAction访问了此内容UITableViewController UITableViewController。我的@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)") } 中只有一个部分,但无论如何都没关系,因为您可以自己轻松设置和分配。

UIButton

每当我点按UITextField时,它都会向我提供public class SomeClass() { public static void main(String[] args){ MVEL.eval("System.out.println(\"I am inside main method\");method1();"); } public static void method1(){ System.out.println("I am inside method 1"); } } 内文字的更新值。