繁体   English   中英

从Swift中的UIButton选择到ViewController

[英]Segue to a ViewController from a UIButton in Swift

我有一个TabViewController,它具有三个选项卡,这会导致三个ViewController。

我可以使用TVC的实际选项卡按钮进行搜索。 但是,我也想使用UIButton来选择其中一个选项卡。 我在一个ViewController中有一个按钮,但我想选择另一个按钮,但不使用Tab按钮。

我取得了部分成功。 我的意思是说,VC出现了,但是TabBar不存在!

UIButton所在的视图控制器的代码如下:

import UIKit

class HomeView: UIViewController {

    @IBOutlet var startBtn: UIButton! //Define the start button as a variable
    @IBOutlet var homeText: UILabel! //Define the text on the home screen

    override func viewDidLoad() {
        super.viewDidLoad()
        setBackground(); //Set background image
        setStartBtn();
        setHomeText();
    }

    func setBackground() {

        // Apply the insets…
        let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
        backgroundImage.image = UIImage(named: "Background.png")
        backgroundImage.contentMode = UIView.ContentMode.scaleAspectFill
        self.view.insertSubview(backgroundImage, at: 0)
    }

    func setStartBtn() {
        let startBtnText = NSLocalizedString("Start Test", comment: "")
        startBtn.addTarget(self, action: #selector(self.clickStart(_:)), for: .touchUpInside) //Add a target and action of the start buton
        startBtn.setTitle(startBtnText, for: [])
    }

    func setHomeText() {
        let homeTextStr = NSLocalizedString("Home Text", comment: "")
        homeText.text = homeTextStr
    }

    @objc func clickStart(_ sender: UIButton) {

    }
}

解:

我需要的“单击开始”功能看起来像这样(由于下面接受的答案)。

@objc func clickStart(_ sender: UIButton) {
    self.tabBarController?.selectedIndex = 1 // 1 is the second tab
}

这使我可以从视图中的UIButton移至第二个选项卡栏项

您需要将每个vc嵌入到navigationController内的选项卡中,然后使用它来导航到嵌套的vc

@objc func clickStart(_ sender: UIButton) { 
   let vc = self.storyboard!.instantiateViewController(withIdentifier: "VCID") // set id for the destination vc
   self.navigationController?.pushViewController(vc,animated:true) 
}

这可以导航到选项卡内的另一个vc

self.tabBarController?.selectedIndex = 1 // 1 is the second tab

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM