在自定义UITableViewCell中管理UITextField的代理

时间:2012-07-16 22:49:59

标签: iphone objective-c ios ipad uitableview

所以我已经看了很多,这里的任何内容似乎都没有解释这样做的正确方法。我在自定义UITableViewCell中有7个UITextField。

我的问题是:管理这些UITextFields委托的正确方法是什么?

由于自定义单元在技术上属于"模型"在项目的一部分,我宁愿控制UITableView的控制器也控制表格单元格中的文本字段,但我无法弄清楚如何设置文本字段的委托(在UITableViewCell的子类)到这个视图控制器。

让UITableViewCell的子类符合UITextField委托并管理其中的所有内容是不是不好的做法?如果是这样,我该怎么做呢?

谢谢,任何帮助都将不胜感激。

5 个答案:

答案 0 :(得分:16)

将单元格文本字段的委托设置为视图控制器时,应该没有问题。

这是你需要做的:

1)视图控制器需要实现UITextFieldDelegate协议

2)为自定义单元格中的文本字段声明属性

@property (nonatomic, retain) IBOutlet UITextField *textField;

3)然后在方法cellForRowAtIndexPath

中将视图控制器设置为文本字段的委托
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";

    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) 
    {  
        // use this if you created your cell with IB
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil] objectAtIndex:0];   

        // otherwise use this  
        cell = [[[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 


        // now set the view controller as the text field delegate  
        cell.textField.delegate = self;
    }

    // configure cell...

    return cell;
}

答案 1 :(得分:6)

在我看来,单元格应该管理键盘,因为它是持有UITextField的键盘。您可以将单元格设置为UITextField委托。在我自己的应用程序中,我已经完成了这个,然后让我的单元格拥有它自己的委托。 UITextField的任何方法或控制器应该处理的任何新方法都可以通过单元委托传递给控制器​​。

通过这种方式,单元格仍然可以是通用的,而无需了解应用程序实际执行的操作。

答案 2 :(得分:0)

我的建议是每个textField的“标记”(即设置标记),其值为编码表中的section,row和7-of-7文本视图,然后使UIViewController成为委托。 / p>

所以你需要限制它们的大小 - 比如你永远不会超过100行。所以你把它编码为:

.tag = 1000 * section + 100 * row +

当您收到消息时,您可以使用方法/函数获取标记并将其解码为section,row,tag,并执行您需要完成的操作。

答案 3 :(得分:0)

在TableViewController的.h文件的<UITextFieldDelegate>末尾声明TableViewController作为委托包括@interface

@interface MyTableViewController : UITableViewController <UITextFieldDelegate>

然后,通过按住Ctrl键拖动@interface下的每个字段来连接文本字段。每个UITextField都通过IBOutlet连接到其各自的属性。最后,在.m文件中包含以下函数,以显示委托您要返回的字段....

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

答案 4 :(得分:0)

Swift版本(基于Eyal的答案)

class MyViewController: UIViewController, ... , UITextFieldDelegate {

    @IBOutlet var activeTextField: UITextField!  //doesn't need to connect to the outlet of textfield in storyboard

    ....

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    ....

    var cellTextField = self.view.viewWithTag(101) as? UITextField
    cellTextField!.delegate = self;
    ....
}