简体   繁体   中英

How can I get the IndexPath of a textField in Swift

I am using a sectioned tableView in my app, each row of the tableView contains a textField, when textFieldDidBeginEditing I need to know the indexPath of that textField. Using the tag can only get the section or row, and creating an extension of UITextField doesn't allow you to add variables. How can I get this done?

There are way to do it but it's bad design anyway, suggest you to put the textfield delegate inside the cell class.

You can try to get the exact cell/contentView with textField.superview , convert it to MyTableViewCell , then use tableView.indexPath(for: cell) to get index.

No need for tags to do it.

Example:

var view: UIView = textField
while !view.isKind(of: UITableViewCell.self), let superView = view.superview {
    view = superView
}
if let view = view as? MyTableViewCell {
   //Do sth
}

I like to walk from the text field to the cell and ask the table view for its index path.

extension UIResponder {
    func next<T:UIResponder>(ofType: T.Type) -> T? {
        let r = self.next
        if let r = r as? T ?? r?.next(ofType: T.self) {
            return r
        } else {
            return nil
        }
    }
}

And

func textFieldDidBeginEditing(_ textField: UITextField) {
    if let cell = textField.next(ofType: MyCell.self) {
        if let ip = self.tableView.indexPath(for:cell) {
           // whatever
        }
    }
}

in cellForRow

var section = indexPath.section + 1
var row = indexPath.row + 1
index = Int("\(section)0\(row)")!

setting the textFields' tags to index

in textFieldDidBeginEditing

let indexString = "\(textField.tag)"
let parts = indexString.components(separatedBy: "0")
let row = Int(parts[1])! - 1
let section = Int(parts[0])! - 1

Easiest way to get indexPath of cell that contain textfield

func getIndexPathFromView(_ sender : UIView) -> IndexPath? {
    let point = sender.convert(CGPoint.zero, to: self.tblView)
    let indexPath = self.tblView.indexPathForRow(at: point)
    return indexPath
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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