iOS在UITableViewCell上获取子视图的参考

时间:2013-09-02 09:30:34

标签: ios uitableview

我正在使用UITableView创建自定义控件。此控件只是一个表视图,在一个部分中有多行。我们称之为MyCustomControl

在表格视图的每个单元格中,我添加了UITextField控件。

----------------
| ------------ |
|| Text Field || -> CELL
| ------------ |
----------------

此单元格只是默认UITableViewCell,我使用[cell addSubview:textField];

添加了文本字段

我使用以下方法访问表视图上的每个文本字段组件:

- (UITextField*) textFieldAtIndex:(NSInteger)index
{
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index inSection:0];

    UITableViewCell* cell = [self tableView:[self containerTableView] cellForRowAtIndexPath:indexPath];

    UITextField* textField = [[cell subviews] lastObject];

    return textField; // It should returning the reference of textField right??
}

曾几何时,我在项目中的某个视图控制器中使用此MyCustomControl

- (void) viewDidLoad
{
    [super viewDidLoad];

    CGPoint origin = CGPointMake(100.f, 100.f);

    CGFloat width = 200.f;

    // Create custom control with text field generated as many as given parameter
    MyCustomControl* textGroup = [[MyCustomControl alloc] initWithOrigin:origin width:width textFieldCount:2];

    // Here is the problem, I try to set current view controllers's text fields 
    // with the text field generated by MyCustomControl.
    // Text field returned are new text field with same properties instead of reference.
    self.txtUsername = [textGroup textFieldAtIndex:0]; // Text Field are copied!
    self.txtPassword = [textGroup textFieldAtIndex:1]; // Not return a pointer!

    [self.txtUsername setDelegate:self]; // Fail
    [self.txtPassword setDelegate:self]; // Fail

    [[self view] addSubview:textGroup]; 

    [[self view] addSubview:[self txtUsername]]; // New text field appeared on view
}

我希望完全控制从方法MyCustomControl访问的textFieldAtIndex:中的文本字段,但我没有引用该文本字段,而是在视图控制器中获得了一个新的文本字段副本。而且我不能为该文本字段设置委托,也不能像其文本一样设置所有其他内容。

如何从此表格视图单元格中的文本字段中获取引用?

3 个答案:

答案 0 :(得分:3)

将自定义单元格类和文本字段的IBOutlet设置为它 在cellForRowAtIndexPath

中隐藏此文本字段

Textfield touchDown操作方法在您创建新方法时设置它(默认情况下,按钮与touchUpInside相同 - 您可以通过选择控件并单击来查看此选项在连接检查员)

从下面的方法,您可以获得文本字段的参考

- (IBAction)actionTextField:(id)sender {

UIView *view = sender.superview;
while (view && ![view isKindOfClass:[UITableViewCell self]]) view = view.superview;

UITableViewCell *cell = (UITableViewCell *)view;
indexPathForDeletion = [self.tableViewListViewVC indexPathForCell:cell];
NSLog(@"cell is in section %d, row %d", indexPathForDeletion.section, indexPathForDeletion.row);


}

答案 1 :(得分:3)

检查我的答案,他们想要一个文本字段,但过程是相同的,比其他一些解决方案更清晰:

How to get UITableView Label Text string - Custom Cell

假设您知道索引路径。

答案 2 :(得分:1)

自定义控件类中的tableview单元格不是在创建自定义类的实例时创建的,因此它建议您在创建之前分配文本字段,这是我猜的问题。    要从每个单元格中获取文本字段的引用,您可以在创建单元格时为每个文本字段指定标记值,并可以在当前控制器中随时通过标记值访问它们。