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

问题描述:

所以我已经环视了一下,这里没有任何东西似乎解释了完成此操作的正确方法。我有一个自定义的UITableViewCell中的7个UITextFields。在自定义UITableViewCell中管理UITextFields的代理

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

由于自定义单元在技术上是项目“模型”部分的一部分,我宁愿让控制器控制UITableView也控制表格单元格中的文本字段,但我无法弄清楚如何设置该视图控制器的文本字段的代表(在UITableViewCell的子类中创建)。

只是让UITableViewCell的子类符合UITextField委托并管理那里的所有东西是不好的做法?如果是这样,我该怎么做呢?

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

我的建议是将每个textField的“标记”(即设置标记)与一个值编码表中的部分,行和七个文本视图中的一个值,然后使UIViewController成为委托。

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

.TAG = 1000 *节+ 100 *行+

当你得到一个消息,你可以有一个方法/函数使用标记并解码成段,行,标签,并做你需要做的事情。

要声明您的TableViewController作为代表包括<UITextFieldDelegate>在您的@interface在TableViewController的.h文件的末尾。

@interface MyTableViewController : UITableViewController <UITextFieldDelegate> 

然后,通过按住Ctrl拖动@interface下的每个字段来连接文本字段。每个UITextField都通过IBOutlet连接到其各自的属性。最后,在.m文件包括下列函数来显示你想返回现场委托....

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

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

通过这种方式,在不知道应用程序实际正在做什么的情况下,单元仍然可以是通用的。

+1

我同意。要做到这一点,只需在UITableViewCell实现的初始化中设置委托。例如,在awakeFromNib调用中,只需添加self.YourTextField.delegate = self。 – JeffB6688 2017-04-14 19:00:20

+0

同意这是做到这一点的正确方法。 – GeneCode 2017-04-20 07:46:39

你不应该有一个问题,设置该单元格的文本字段的代表作为您的视图控制器。

这就是你需要做什么:

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

谢谢!为我工作 – 2016-12-13 17:40:59

Swift version(基于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; 
    .... 
}