我已经创建了一个按钮,我想知道如何以编程方式为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("...")
}
答案 0 :(得分:0)
如果要在按下按钮后过渡到另一个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)
}
答案 1 :(得分:0)
可以通过3种方式显示新的View Controller:
呈现视图控制器:
@objc func buttonAction(sender: UIButton!) {
let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
self.present(destinationVC, animated: true, completion: nil)
}
从情节提要中执行Segue:
如果您已经具有要在情节提要中显示的View Controller,并且它具有从源VC到目标VC的序列,则可以在序列中添加一个标识符并执行此操作...
@objc func buttonAction(sender: UIButton!) {
self.performSegue(withIdentifier: "MySegueIdentifier", sender: self)
}
将View Controller推入堆栈(仅当您的原始VC嵌入在Navigation Controller中时才有效):
@objc func buttonAction(sender: UIButton!) {
let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
self.navigationController?.pushViewController(destinationVC, animated: true)
}