ios - 获取此单元格中单元格或文本字段的位置

标签 ios objective-c uitableview uitextfield

我有一个 Split View Controller :view & tableview。在此 TableView 中,我有带有文本字段的自定义单元格。我不知道我会有多少个细胞,所以它会自动生成。现在我正在尝试滚动到文本字段,当它成为 FirstResponder 时。我试过这样的事情:

-(void) textFieldDidBeginEditing:(UITextField *)textField {
    CGPoint focusOnTextField = CGPointMake(0, 300 + textField.frame.origin.y);
    [scroller setContentOffset: focusOnTextField animated: YES];
}

300px - 我的 TableView 的起始位置。一切似乎都很好,但是 textField.frame.origin.y 总是等于 0(就像 bounds.origin.y 顺便说一句)。

我想我可以解决一个问题,如果获取单元格的位置,哪个文本字段处于事件状态,然后将 textField.frame.origin.y 替换为 cell.frame.origin.y 或类似的东西。

============================================ =======================

我忘了说我的 tableviews 滚动被禁用了。我遵循您的建议和代码示例并像这样解决它:

- (UITableViewCell *)cellWithSubview:(UIView *)subview {

    while (subview && ![subview isKindOfClass:[UITableViewCell self]])
        subview = subview.superview;
    return (UITableViewCell *)subview;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *activeCell = [self cellWithSubview:textField];

    float offsetValueY = 200 + activeCell.origin.y;
    CGPoint focusOnTextField = CGPointMake(0, offsetValueY);
    [scroller setContentOffset:focusOnTextField animated:YES];
}

知道吗?它的工作! :-) 但它产生了一个新问题。当我开始编辑文本字段时,滚动条首先跳到顶部,然后才转到正确的位置。当我写 [scroller setContentOffset:focusOnTextField animated:NO]; 并且这个问题消失了,但是滚动条没有平滑移动。这对我来说很糟糕 :-) 那么我们该如何解决呢?

最佳答案

这是滚动到包含文本字段的单元格的方法...

// find the cell containing a subview.  this works independently of how cells
// have been constructed.

- (UITableViewCell *)cellWithSubview:(UIView *)subview {

    while (subview && ![subview isKindOfClass:[UITableViewCell self]])
        subview = subview.superview;
    return (UITableViewCell *)subview;
}

您的想法是正确的,可以在编辑开始时触发该操作。只需使用单元格...

- (void)textFieldDidBeginEditing:(UITextField *)textField {

    // find the cell containing this text field
    UITableViewCell *cell = [self cellWithSubview:textField];

    // now scroll using that cell's index path as the target
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

关于ios - 获取此单元格中单元格或文本字段的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547549/

相关文章:

objective-c - 绘制许多 MKOverlay 时的性能问题

ios - 审核通过后如何在iTunesConnect新界面设置具体发布日期?

ios - 通知触发时播放视频

ios - 如何在 iOS 中播放 .h264

iOS Metal 。如何将 'half' 格式用于所有颜色作品?

objective-c - 如何制作在 iPhone 中存储发送和接收消息的应用程序

ios - 表格 View 单元格的圆角半径

iphone - 优化自定义 UITableViewCell 创建

ios - 为什么 UITableView 在从远程服务器加载更多行时自动调整行高 "scrolls up and then down"?

objective-c - 对象返回 NSArrayReverseEnumerator。导致无法识别的选择器发送到实例