Swift 4:如何实现输入文本跳转后设为导航栏标题?
实现TextField输入文本跳转后设置第二个页面导航栏标题(Swift)
嘿,刚入门iOS开发的话,这个需求其实很容易搞定,咱们一步步来,保证你能看懂:
第一步:给FirstViewController的TextField做关联
首先打开你的FirstViewController.swift,先给界面上的TextField关联一个IBOutlet(把界面输入框和代码绑定起来):
@IBOutlet weak var inputTextField: UITextField!
然后咱们需要一个触发跳转的方式——可以是按钮点击,也可以是用户在输入框按回车,两种方式都给你写出来:
方式1:按钮点击跳转
给界面上的按钮关联一个IBAction:
@IBAction func goToSecondVC(_ sender: UIButton) { // 跳转逻辑后面补充 }
方式2:按回车跳转
如果想用回车触发,得让FirstViewController遵守UITextFieldDelegate协议,然后实现回车回调:
// 先在类声明里添加协议 class FirstViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var inputTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // 设置输入框的代理为当前控制器 inputTextField.delegate = self } // 回车触发的方法 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() // 收起键盘 goToSecondVC(UIButton()) // 调用跳转方法 return true } @IBAction func goToSecondVC(_ sender: UIButton) { // 跳转逻辑后面补充 } }
第二步:给SecondViewController准备接收数据的属性
打开SecondViewController.swift,添加一个可选字符串属性,用来接收从第一个页面传过来的文本:
class SecondViewController: UIViewController { // 用来接收标题文本 var navigationTitle: String? override func viewDidLoad() { super.viewDidLoad() // 后面在这里设置导航栏标题 } }
第三步:跳转时传值并设置标题
这里分两种常见的跳转场景,你选自己在用的方式就行:
场景1:用Storyboard Segue跳转
- 打开Storyboard,选中FirstViewController到SecondViewController的Segue,在右侧Attributes Inspector里给它设置一个标识符,比如
goToSecondVC(要和代码里的对应上)。 - 回到FirstViewController.swift,实现
prepare(for:sender:)方法,在跳转前完成传值:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // 判断是不是咱们设置的那个Segue if segue.identifier == "goToSecondVC" { // 把目标控制器转成SecondViewController类型 guard let secondVC = segue.destination as? SecondViewController else { return } // 获取输入框的文本,为空的话给个默认值(避免导航栏空白) let inputText = inputTextField.text ?? "默认标题" // 把文本传给SecondVC的属性 secondVC.navigationTitle = inputText } }
- 最后在SecondViewController的
viewDidLoad里设置导航栏标题:
override func viewDidLoad() { super.viewDidLoad() // 把接收的文本设置成导航栏标题 navigationItem.title = navigationTitle }
场景2:纯代码跳转(不用Storyboard)
如果是完全用代码创建控制器跳转,直接在FirstViewController的跳转方法里写:
@IBAction func goToSecondVC(_ sender: UIButton) { // 创建SecondViewController实例 let secondVC = SecondViewController() // 获取输入文本,为空给默认值 let inputText = inputTextField.text ?? "默认标题" // 传值 secondVC.navigationTitle = inputText // 用导航控制器push过去(注意FirstViewController必须在导航栈里!) navigationController?.pushViewController(secondVC, animated: true) }
同样在SecondViewController的viewDidLoad里设置标题就行。
新手注意点
- 一定要确保你的FirstViewController是被包裹在
UINavigationController里的,不然导航栏和push跳转都不会生效哦! - 可以给TextField设置个占位符(比如在Storyboard里的Placeholder写“请输入导航栏标题”),提示用户输入。
- 处理空文本的情况很重要,不然用户啥也没输入的话,导航栏会空白,给个默认值会更友好。
内容的提问来源于stack exchange,提问作者user9606399
相关产品推荐
相关产品推荐

