How to get cell indexpath in uitextfield Delegate Methods?

问题描述 投票:0回答:11

我在自定义单元格中有两个文本字段如何在文本字段委托方法中获取 Tableview 单元格的索引路径值我想从用户那里获取输入值并将其保存到相关对象。用户可以通过单击单元格中的按钮(添加更多)来添加更多单元格..

enter image description here

提前致谢...

iphone objective-c uitableview user-interface uitextfield
11个回答
18
投票

更新到 iOS7!

现在 iOS7 有了新功能code 应该是:

UITableViewCell *textFieldRowCell;

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
    // Load resources for iOS 6.1 or earlier
    textFieldRowCell = (UITableViewCell *) textField.superview.superview;

} else {
    // Load resources for iOS 7 or later
    textFieldRowCell = (UITableViewCell *) textField.superview.superview.superview; 
   // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Whoola!
}

NSIndexPath *indexPath = [self.tableView indexPathForCell:textFieldRowCell];

13
投票

更动态的解决方案(没有硬编码的超级视图级别和不同 iOS 版本的相同代码)。

此外,如果单元格不可见,

indexPathForCell:
将不起作用,因此我使用
indexPathForRowAtPoint:
作为解决方法。

//find the UITableViewcell superview
UIView *cell = textField;
while (cell && ![cell isKindOfClass:[UITableViewCell class]])
    cell = cell.superview;

//use the UITableViewcell superview to get the NSIndexPath
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];

10
投票

这就是我一直在做的事情并且运气更好。我抓住了 textField 框架的起源。将其转换为一个点。然后将该点转换为索引路径。

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGPoint origin = textField.frame.origin;
    CGPoint point = [textField.superview convertPoint:origin toView:self.tableView];

    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];

    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

}

4
投票

尝试使用此方法从您的

tableview
控制器动态获取文本字段

 #pragma mark - Get textfield indexpath
- (NSIndexPath *)TextFieldIndexpath:(UITextField *)textField
{
    CGPoint point = [textField.superview convertPoint:textField.frame.origin toView:self.TblView];
    NSIndexPath * indexPath = [self.TblView indexPathForRowAtPoint:point];
    NSLog(@"Indexpath = %@", indexPath);
    return indexPath;
}

2
投票

要获取 indexPath,请尝试以下代码。

    UIView *contentView = (UIVIew *)[textfield superview];
    UITableViewCell *cell = (UITableViewCell *)[contentView superview];
    if(IS_IOS7_OR_GREATER) {
        cell = (UITableViewCell *)[[contentView superview] superview];
    }
    NSIndexPath *indexPath = [self.tableview indexPathForCell:cell];

就这样你就完成了。

简单来说,

NSIndexPath *indexPath = [self.tableview indexPathForCell:(UITableViewCell *)[(UIVIew *)[textfield superview] superview]];

if(IS_IOS7_OR_GREATER) {
    cell = (UITableViewCell *)[[[textfield superview] superview] superview];
}

检查更新的答案。


2
投票

万一像我这样的人需要@Kerkness 的答案(这个答案对我很有效):

func textFieldDidBeginEditing(_ textField: UITextField) {
    let origin: CGPoint = textField.frame.origin
    let point: CGPoint? = textField.superview?.convert(origin, to: tableView)
    let indexPath: IndexPath? = tableView.indexPathForRow(at: point ?? CGPoint.zero)
    tableView.scrollToRow(at: indexPath!, at: .middle, animated: true)
}    

它应该足够直截了当:你明白了,然后你得到了 indexPath 并用它做任何你需要的事情!


1
投票

将单元格索引路径值设置为

UITextField
tag
属性,您可以在委托方法中访问索引路径,如
textfield.tag


1
投票

您可以在 cellForRowAtIndexPath: 中设置文本字段的标签,以便它存储单元格和文本字段的信息

例如:如果是第4行的单元格,则第一个和第二个文本框的标签可以分别为41和42。同样,文本字段的标签应该是第 5 行的 51 和 52 等等......

然后在 textfield delegate 方法中,你可以获取 textfield.tag 来标识活动的 textfield。


1
投票

这可以在 Objective-C 运行时中针对任何实例(不必是 UITextField)以及任何关联对象(不必是 NSIndexPath)完成。

对于这个问题,我们可以创建一个类别

UIView+RepresentingIndexPath
.

我们的界面允许我们设置和检索 NSIndexPath:

@interface UIView (RepresentingIndexPath)
- (void)representIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)representedIndexPath;
@end

我们的实现使用 Objective-C 关联对象来设置和检索视图上的索引路径:

#import "UIView+RepresentingIndexPath.h"
#import <objc/runtime.h>

static char IndexPathKey;

@implementation UIView (RepresentingIndexPath)

- (void)representIndexPath:(NSIndexPath *)indexPath
{
    objc_setAssociatedObject(self, &IndexPathKey, indexPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSIndexPath *)representedIndexPath
{
    return objc_getAssociatedObject(self, &IndexPathKey);
}

@end

在行动中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextFieldCell" forIndexPath:indexPath];
    [cell.textField addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
    [cell.textField representIndexPath:indexPath];
    return cell;
}

- (void)textFieldTextChanged:(UITextField *)sender
{
    NSIndexPath *indexPath = [sender representedIndexPath];
    NSLog(@"%@", indexPath);
}

💣

最后一点!如果您可以在不这样做的情况下实现您想要做的事情,那么真的应该避免在运行时乱搞。只是想我会添加另一个解决方案!


1
投票

我在搜索如何找到 UITextField 内的单元格的索引路径时找到了这个答案。

所以,感谢上面的回答,我把我的代码放在这里,希望可能有用。

- (void)searchSelectedIndexPath:(UIView*)view {
    // This allow to find selected index path for a table view cell with a text field inside.
    for (UIView* subview in view.subviews) {
        if ([view isKindOfClass:[UITextField class]]) {
            if ([view isFirstResponder]) {
                UIView *cell = view;
                while (cell && ![cell isKindOfClass:[UITableViewCell class]]) {
                    cell = cell.superview;
                }
                self.selectedIndexPath = [self.tableView indexPathForRowAtPoint:cell.center];
                return;
            }
        }
        [self searchSelectedIndexPath:subview];
    }
}

这样,当键盘通知将被提升时:

- (void)keyboardDidShow:(NSNotification*)notification {
    [self searchSelectedIndexPath:self.tableView];
}

-1
投票

谢谢,@Luka,它工作得很好。 这是swift 4的解决方案,

var selectedIndexPath: IndexPath?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowHide(_ :)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowHide(_ :)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}


func searchSelectedIndexPath(view: UIView) {
    view.subviews.forEach { (subview) in
        if view is UITextView, view.isFirstResponder == true {
            var cell:UIView? = view;
            while cell != nil && !(cell is UITableViewCell) {
                cell = cell?.superview;
            }
            if cell != nil {
                self.selectedIndexPath = self.dashBoardTableView.indexPathForRow(at: (cell?.center)!)
                return
            }
        }
        self.searchSelectedIndexPath(view: subview)
    }
}

// Keyboard notification observer menthod
@objc fileprivate func keyboardWillShowHide(_ notification: NSNotification){
     if notification.name == NSNotification.Name.UIKeyboardWillShow {

        UIView.animate(withDuration: duration, animations: { () -> Void in
            self.selectedIndexPath = nil;
            self.searchSelectedIndexPath(view: self.tableView)
            if let indexpath = self.selectedIndexPath {
                self.tableView.scrollToRow(at: indexpath, at: .top, animated: false)
            } else{
                self.bottomContriant.constant = keyboardHeight
                self.view.layoutSubviews()
            }
        })
    } else {
        self.bottomContriant.constant = 15
        UIView.animate(withDuration: duration, animations: { () -> Void in
            self.view.layoutIfNeeded()
        })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.