繁体   English   中英

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

[英]iOS Getting Reference of Subview on UITableViewCell

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

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

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

这个单元格只是默认的UITableViewCell ,我使用[cell addSubview:textField];添加了文本字段[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
}

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

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

将自定义单元格类和文本字段的IBOutlet设置为它在cellForRowAtIndexPath中的任何位置隐藏此文本字段

TextfieldtouchDown操作方法在创建新方法时设置它(默认情况下,按钮与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);


}

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

如何获取UITableView标签文本字符串 - 自定义单元格

那就是假设您知道索引路径。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM