swift 如何以编程方式添加uibutton动作?

kh212irz  于 2023-05-16  发布在  Swift
关注(0)|答案(2)|浏览(175)

我已经创建了一个按钮,我想知道我如何编程代码的行动UIButton带我到另一个视图控制器?
这就是我目前所拥有的一切:

let getStartedButton: UIButton = {
    let getStartedButton =  UIButton()
    getStartedButton.backgroundColor = UIColor(red:0.24, green:0.51, blue:0.59, alpha:1.0)
    getStartedButton.setTitle("Get Started", for: .normal)
    getStartedButton.titleLabel?.font = UIFont(name: "Helvetica Bold", size: 18)
    getStartedButton.translatesAutoresizingMaskIntoConstraints = false
    getStartedButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

    return getStartedButton
}()

@objc func buttonAction(sender: UIButton!) {
    print("...")
}
p8h8hvxi

p8h8hvxi1#

如果你想在按下按钮后转换到另一个ViewController,你可以用两种方法来完成:
1)present(_:animated:completion:)

@objc func buttonAction(sender: UIButton!) {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "Main") as! SecondViewController
    self.present(vc, animated: true, completion: nil)
}

2)pushViewController(_:animated:)

@objc func buttonAction(sender: UIButton!) {
    let vc = self.storyboard?.instantiateViewController(withIdentifier: "Main") as! SecondViewController
    self.navigationController?.pushViewController(vc, animated: true)
}
enyaitl3

enyaitl32#

有三种方法可以显示新的视图控制器:
1.显示视图控制器:

@objc func buttonAction(sender: UIButton!) {
    let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
    self.present(destinationVC, animated: true, completion: nil)
}

1.从故事板中执行一个Segue:
如果你已经有了你想要在情节串联图板中呈现的视图控制器,并且它有一个从你的源VC到你的目标VC的segue,那么你可以添加一个标识符到segue并这样做。

@objc func buttonAction(sender: UIButton!) {
         self.performSegue(withIdentifier: "MySegueIdentifier", sender: self)
    }

1.将视图控制器推到堆栈上(这仅在原始VC嵌入到导航控制器中时有效):

@objc func buttonAction(sender: UIButton!) {
    let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
    self.navigationController?.pushViewController(destinationVC, animated: true)
}

相关问题