以编程方式返回上一页

时间:2019-01-05 18:22:24

标签: swift navigation

enter image description here我正在为IOS应用创建用户登录页面。我正在尝试以编程方式制作所有内容,而不在主故事板上使用segue。正如您在代码中看到的那样,我设法转到了下一页,并创建了一个自定义的左后栏项目。但是,当我单击该按钮时,我不知道如何返回首页。我在下面附上了我的故事板和应用程序的屏幕截图。您能告诉我如何通过单击X按钮返回第一页吗? 这是我的代码:

导入UIKit

FirstPage类:UIViewController {

let hgt = UIScreen.main.bounds.height/2


private let loginSignup: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Login or Sign Up", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
    button.setTitleColor(.green, for: .normal)
    button.addTarget(self, action: #selector(loginSignupBtn), for: .touchUpInside)
    return button
}()

@objc private func loginSignupBtn() {
    let vc = self.storyboard!.instantiateViewController(withIdentifier: "Login") as! Login
    vc.loadViewIfNeeded()
    self.navigationController?.pushViewController(vc, animated: true)
    self.navigationController?.isNavigationBarHidden = false
    let backItem = UIBarButtonItem(title: "X ", style: UIBarButtonItem.Style.done, target: nil, action: nil)
    let font = UIFont.boldSystemFont(ofSize: 26)
    backItem.setTitleTextAttributes([NSAttributedString.Key.font:font] ,for: .normal)
    backItem.tintColor = UIColor.green
    vc.navigationItem.leftBarButtonItem = backItem
}
override func viewDidLoad() {
    super.viewDidLoad()
    setupLayout()
}
override func viewWillAppear(_ animated: Bool) {

}
private func setupLayout() {
    let topImageContainerView = UIView()
    //topImageContainerView.backgroundColor = .yellow
    view.addSubview(topImageContainerView)
    //enable auto layout
    topImageContainerView.translatesAutoresizingMaskIntoConstraints = false
    topImageContainerView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    topImageContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    topImageContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    topImageContainerView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true
    view.addSubview(loginSignup)
    loginSignup.translatesAutoresizingMaskIntoConstraints = false
    loginSignup.topAnchor.constraint(equalTo: view.topAnchor,constant:hgt/2).isActive = true
    loginSignup.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    loginSignup.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    loginSignup.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5).isActive = true

}

}

enter image description here

1 个答案:

答案 0 :(得分:0)

在这里,您需要在单击x按钮时添加目标和选择器

let backItem = UIBarButtonItem(title: "X ", 
  style: UIBarButtonItem.Style.done,
   target: self, action:#selector(goBack))

@objc func goBack(_ bar:UIBarButtonItem) {
   self.navigationController?.popToRootViewController(animated:true)
}