How to get cell indexpath in uitextfield Delegate Methods?

后端 未结 11 1023
南旧
南旧 2020-12-08 22:56

I have two textfields in a custom cell how to get the indexpath value of Tableview cell in textfield delegate methods I want to get the input value from user and save it to

11条回答
  •  孤街浪徒
    2020-12-08 23:06

    Thanks, @Luka, it works in a great way. Here is the swift 4 solution,

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

提交回复
热议问题