步驟:
@IBOutlet weak var AddBookName: UITextField!{
didSet{
// 設定好textfield的tag
AddBookName.tag = 1
// 設定firstResponder
AddBookName.becomeFirstResponder()
AddBookName.delegate = self
}
}
@IBOutlet weak var AddBookISBN: UITextField!{
didSet{
AddBookISBN.tag = 2
AddBookISBN.delegate = self
}
}
@IBOutlet weak var AddBookAuthor: UITextField!{
didSet{
AddBookAuthor.tag = 3
AddBookAuthor.delegate = self
}
}
// 繼承UITextFieldDelegate 使用按下Return到下一個textfield欄位func(textFieldShouldReturn)
class BookAddViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate{
func textFieldShouldReturn(_ textField:UITextField) -> Bool{
if let nextTextField = view.viewWithTag(textField.tag + 1){
// 取消resignFirstResponder
textField.resignFirstResponder()
// 下一個textField變成FirstResponder
nextField.becomeFirstResponder()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
成果展示: