How to find which tableview is editing in textFieldDidEndEditing?

后端 未结 2 1306
不思量自难忘°
不思量自难忘° 2021-01-24 21:32

I am using 2 tableviews

both have textfiled in tableviewcell,

I am getting text of textfield in textFieldDidEndEdit

相关标签:
2条回答
  • 2021-01-24 22:00

    Forget about traversing the view hierarchy; it is error prone and the exact details may change in the future (and break your app horribly).

    Original Answer (for posterity)

    Instead, try this:

    1. Get the text field's location on screen:

      // Center on text field's own coordinate system
      let position = textField.frame.center
      
      // Center on Window's coordinate system
      let positionOnWindow = textField.convert(position, to: nil)
      
    2. Convert that point to the table view's coordinate system, and see if it corresponds to a row:

      let positionInTable = tableView1.convert(positionOnWindow, from: nil)</strike>
      
      if let indexPath = tableView1.indexPathForRow(at: positionInTable) {
          // Text field is inside a row of table view 1
      } else {
          // Otherwise
      }
      

    Note: Code above is untested. May contain compiler errors.

    Assuming both code snippets run on the same class (your table view delegate, data source and text field delegate) there should be no problem passing the value of positionOnWindow around (it can all happen inside the text field delegate method).

    Better Answer

    As duly pointed by @rmaddy in the comments, the code above is too roundabout; you can directly get the position with:

    let positionInTable = tableView1.convert(textField.frame.center, from: textField)
    

    (no need the trip to the window's coordinate system and back)

    0 讨论(0)
  • 2021-01-24 22:01

    Swift 3.x

    Assuming your hierarchy of textFiled is:

    TextField->Cell->TableView

    Write this line of code in textFieldDidEndEditing

    print(textField.superview?.superview)
    if textField.superview?.superview == myTable1 {
    
    }
    else if textField.superview?.superview == myTable2 {
    
    }
    else {
    
    }
    
    0 讨论(0)
提交回复
热议问题