从Swift中的UIButton查看ViewController

问题描述 投票:1回答:1

我有一个TabViewController有三个Tabs,它们导致三个ViewControllers。

我可以使用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移动到第二个标签栏项

ios swift uibutton uitabbarcontroller segue
1个回答
2
投票

您需要在navigationController中的选项卡中嵌入每个vc,然后使用它来导航到嵌套的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
© www.soinside.com 2019 - 2024. All rights reserved.