iOS中如何在TableView表单的TextField间切换光标?
Hey there! I spot the issue in your current code—when you tap the "Next" key on the keyboard, you're just re-focusing the same text field instead of switching to the next one in your TableView. Let's get this sorted out.
What's Wrong with the Current Code?
Your textFieldShouldReturn method calls textField.becomeFirstResponder() for the "Next" case, which keeps the focus on the active text field. We need to instead locate the next text field in the TableView and transfer focus to it.
Updated Solution Code
Here's the revised textFieldShouldReturn method, plus a quick check to make sure we handle edge cases properly:
func textFieldShouldReturn(_ textField: UITextField) -> Bool { let currentRow = textField.tag if textField.returnKeyType == .next { let nextRow = currentRow + 1 // Make sure we don't go beyond the last row of the table guard nextRow < self.arrayData.count else { textField.resignFirstResponder() return true } let nextIndexPath = IndexPath(row: nextRow, section: 0) // Optional: Scroll to the next cell so it's visible to the user tblView.scrollToRow(at: nextIndexPath, at: .none, animated: true) // Grab the next cell and activate its text field if let nextCell = tblView.cellForRow(at: nextIndexPath) as? cellTextField { nextCell.tfValue.becomeFirstResponder() } } else { // For the "Done" key, dismiss the keyboard textField.resignFirstResponder() } return true }
Key Notes to Ensure This Works
- Tag Setup: Your existing code sets
cell.tfValue.tag = indexPath.rowincellForRowAt—this is perfect, as we use the tag to track which row's text field is active. - Cell Access: Make sure your
cellTextFieldclass has thetfValueproperty accessible (it should be an@IBOutletmarked as internal or public). - Array Bounds Check: The
guardstatement prevents us from trying to access a row that doesn't exist (e.g., if the user taps Next on the second-to-last row). - Optional Scrolling: The
scrollToRowcall ensures the next text field is visible to the user, even if it's off-screen—this improves the overall user experience.
内容的提问来源于stack exchange,提问作者Rj19
相关产品推荐
相关产品推荐

