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



我创建了一个按钮,我想知道如何以编程方式编写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("...")
}

如果要在按下按钮后过渡到另一个视图控制器,可以通过两种方式执行此操作:

1( 呈现(_:动画:完成:(

@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)
}

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

  1. 演示视图控制器:

    @objc func buttonAction(sender: UIButton!) {
    let destinationVC = self.storyboard?.instantiateViewController(withIdentifier: "DestinationViewController") as! DestinationViewController
    self.present(destinationVC, animated: true, completion: nil)
    }
    
  2. 从故事板执行 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)
    }
    

最新更新