【问题标题】:How to get cell indexpath in uitextfield Delegate Methods?如何在 uitextfield 委托方法中获取单元格索引路径?
【发布时间】:2012-09-01 09:26:44
【问题描述】:

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

在此先感谢...

【问题讨论】:

标签: iphone objective-c uitableview user-interface uitextfield


【解决方案1】:

更新到 iOS7!

iOS7 的新功能现在代码应该是:

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];

【讨论】:

    【解决方案2】:

    更动态的解决方案(没有硬编码的超级视图级别,不同 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];
    

    【讨论】:

      【解决方案3】:

      这就是我一直这样做的方式,并且运气更好。我抓住了 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;
        }
        

        【讨论】:

          【解决方案5】:

          要获取 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];
          }
          

          检查更新的答案。

          【讨论】:

          • 我对这种情况有一个疑问
          • 是的,您有什么疑问?您可以将其作为问题发布吗?
          【解决方案6】:

          将单元格索引路径值设置为UITextFieldtag属性,您可以在textfield.tag等委托方法中访问索引路径

          【讨论】:

          • 但是我有两个文本字段,如果我可以按照你说的那样使用它
          • 两个文本字段都将在标签中具有唯一的索引路径。然后您可以检查占位符以确定哪个是 url,哪个是名称 textfield.like this NSLog(@"%@",self.textField.placeholder); if([self.textField.placeholder isEqualToString:@"输入名称"])
          • 我想你想让我知道你是否仍然坚持下去
          【解决方案7】:

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

          例如:如果是第 4 行的单元格,则第 1 和第 2 文本字段的标签可以分别为 41 和 42。同样,第 5 行的文本字段标签应为 51 和 52,依此类推...

          然后在 textfield 委托方法中,您可以获取 textfield.tag 来识别活动的文本字段。

          【讨论】:

          • 最简单的方法永远是最好的!
          【解决方案8】:

          这可以在 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);
          }
          

          ?

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

          【讨论】:

            【解决方案9】:

            我找到了这个答案,搜索如何在 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];
            }
            

            【讨论】:

              【解决方案10】:

              如果像我这样的人需要@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 并用它做任何你需要的事情!

              【讨论】:

                【解决方案11】:

                谢谢@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()
                        })
                    }
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-08-10
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-02-02
                  相关资源
                  最近更新 更多