页面跳转需要添加navigationController,方法是在storyBoard视图中点击一个启动视图,点击右下角的 Embed in 按钮即可添加一个navigationController
接下来在视图界面中的按钮 按住Ctrl 拖动指向另外一个界面,在弹窗中选择 show 既可以跳转对应的目标页面。
如果一个页面有多个按钮需要跳转页面,需要在类中判断是否可以跳转,重写方法shouldPerformSegue,该方法控制是否可以跳转页面:
还有一个方法是prepare,方法,是等待shouldPerformSegue返回true的时候紧接着调用,下面的例子演示冲登录页面跳转到登录成功界面(跳转需要用户名和密码不为nil)和注册页面(跳转不需要条件)
loginVC:
import UIKit
/**
登录界面
*/
class LoginVC: UIViewController {
@IBOutlet weak var errorTip: UILabel!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var username: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "loginSuccess" {
let target = segue.destination as? SuccessVC;
target?.text = "登录成功"
}
}
// 是否决定进行页面跳转
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if(identifier == "register") {
return true;
} else {
// let usernameIsOk = username.text ?? "";
//username.text?.isEmpty
if username.hasText && password.hasText {
errorTip.text = "";
return true;
}
if !username.hasText {
errorTip.text = "用户名不能为空!"
return false;
}
if !password.hasText {
errorTip.text = "请输入密码!"
return false;
}
return false;
}
}
}
successVC:
import UIKit
class SuccessVC: UIViewController {
var text: String = ""
@IBOutlet weak var successLabel: UILabel!
@IBOutlet weak var backButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
successLabel.text = text;
// Do any additional setup after loading the view.
}
@IBAction func backEvent(_ sender: UIButton) {
// self.navigationController?.popViewController(animated: true)
// 退出页面调用dismiss方法退出当前视图
self.dismiss(animated: true) {
print("退出成功");
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}