ios 在自定义 UITableViewCell 中访问 UITextField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4375442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:15:04  来源:igfitidea点击:

Accessing UITextField in a custom UITableViewCell

iphoneobjective-ciosuitableview

提问by Darthtong

I have a UITableViewCell (with associated UITableViewCell sub class, .m & .h) created in IB which contains a UITextField. This UITextField is connected up to an IBOutlet in the UITableViewCell sub class and also has a property. In my table view controller I am using this custom cell with the following code:

我有一个在包含 UITextField 的 IB 中创建的 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;

}

The UITextField displays fine and the keyboard pops up when clicked as expected, but how do I access (get .text property) the UITextField that each row contains? and also how do I handle the 'textFieldShouldReturn' method of the UITextFields?

UITextField 显示正常,按预期点击时键盘会弹出,但我如何访问(获取 .text 属性)每行包含的 UITextField?以及如何处理 UITextFields 的“textFieldShouldReturn”方法?

回答by Rog

I think what the OP is trying to understand is how to access the UITextField value once the user has entered data into each fields. This will not be available at the time the cells are created as suggested by @willcodejavaforfood.

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

I've been implementing a form and trying to make it as user friendly as possible. It is doable but be aware that it can get quite convoluted depending on the number of UITableViewCells / UITextFields you have.

我一直在实现一个表单,并试图使其尽可能用户友好。这是可行的,但请注意,根据您拥有的 UITableViewCells / UITextFields 的数量,它可能会变得非常复杂。

Firstly to your question re: accessing the values of UITextField:

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

1) Make your view controller a <UITextFieldDelegate>

1)让你的视图控制器成为 <UITextFieldDelegate>

2) Implement the following method:

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

I also use a similar syntax to make sure the current edited field is visible:

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

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

And finally, you can handle textViewShouldReturn:in a similar way:

最后,你可以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;
        }           
        ...
}

回答by KingofBliss

In cellForRowAtIndexPath: include this code,

在 cellForRowAtIndexPath: 中包含此代码,

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

Then access the textField using

然后使用访问 textField

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

回答by Priyan Haridas

There is even more simpler way to solve both problems,

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

1.Create a custom uitableviewCell class for the cell, (e.g.textfieldcell)

1.为单元格创建一个自定义的uitableviewCell类,(egtextfieldcell)

2.Now, in the textfieldcell.h file call textFieldDelegate

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

3.In the textfieldcell.m file write textFieldDelegate methods ie

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

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

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

5.(second problem),

5.(第二个问题),

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

6.create a custom delegate method in the MaintableViewController

6.在MaintableViewController中创建自定义委托方法

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

7.In MaintableViewController.m file write the implementation of the delegate method,

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

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

8.call the delegate method in the cell class , and pass the variable in the didendmethod

8.调用cell类中的delegate方法,在didendmethod中传递变量

9.now, assign self to cell.delegate ,when initializing the cell in uitableview

9.现在,在 uitableview 中初始化单元格时,将 self 分配给 cell.delegate

10.thats it you got the variable passed from textfield to the main view, Now do whatever u want with the variable

10.就是这样,您将变量从文本字段传递到主视图,现在对变量做任何您想做的事情

回答by jaytrixz

This is how I managed to get the text inside the UITextFieldinside my custom UITableViewCellin Swift. I accessed this inside my UIButtoninside another custom UITableViewCellthat has an @IBActionon my UITableViewController. I only have one section in my UITableViewControllerbut that doesn't matter anyway because you can easily set and assign this yourself.

这就是我设法在 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)")
}

Whenever I tapped my UIButton, it gives me the updated value of the text inside my UITextField.

每当我点击 my 时UIButton,它都会为我提供 my 中文本的更新值UITextField

回答by SirRupertIII

Thistutorial was helpful to me. You can reference whatever object you need through the tag.

这个教程对我很有帮助。您可以通过标签引用您需要的任何对象。

In the Storyboard drag on a UIImageViewor UITextFieldetc. and set the tag to 100 (whatever you want) then in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathuse the tag to reference it.

在 Storyboard 中拖动 aUIImageViewUITextFieldetc. 并将标签设置为 100(无论你想要什么),然后在你- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath使用标签来引用它。

Here's something you could do, just remember to set the tags in the storyboard:

您可以执行以下操作,只需记住在故事板中设置标签即可:

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

回答by willcodejavaforfood

If you have created a class for your custom cell I'd advise you to work against it.

如果您为自定义单元创建了一个类,我建议您反对它。

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