[英]Swift 5. How present or show ViewController on button touch? Without Storyboard (programmatically)
How can I show()
or persent()
VC on button touch?如何在按钮触摸时
show()
或persent()
VC? What code should I write?我应该写什么代码?
First, using Storyboards一、使用故事板
If you are working with storyboard.如果您正在使用故事板。 You should connect your button view storyboard.
您应该连接按钮视图故事板。
@IBAction fileprivate func handlePresentingView(_ sender: UIButton) {
let vc = SecondVC()
present(vc, animated: true, completion: nil)
}
Second, programmatically二、程序化
1: If you are working programmatically in viewDidLoad
add the following line. 1:如果您在
viewDidLoad
以编程方式工作,请添加以下行。
mybutton.addTarget(self, action: #selector(handlePresentingVC(_:)), for: .touchUpInside)
2: Your action method 2:你的行动方法
@objc func handlePresentingVC(_ sender: UIButton) {
let vc = SecondVC()
present(vc, animated: true, completion: nil)
}
In my example, I'm assuming that you don't have a storyboard file for your
SecondVC
view controller.在我的示例中,我假设您的
SecondVC
视图控制器没有故事板文件。If
SecondVC
is connected to a storyboard view controller, you will need to change the instantiation of yoursecondVC
object inside of your button's action method.如果
SecondVC
连接到故事板视图控制器,您将需要更改按钮操作方法内的secondVC
对象的实例化。
1: Select your SecondVC's view controller in your storyboard. 1:在故事板中选择您的 SecondVC 的视图控制器。
2: Add a Storyboard ID to it. 2:给它添加一个Storyboard ID。
3: Change your button's action method to the following. 3:将按钮的操作方法更改为以下内容。
@objc func handlePresentingVC(_ sender: UIButton) {
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let secondVc = storyboard.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC
present(secondVc, animated: true, completion: nil)
}
In Swift 5 and iOS 13在 Swift 5 和 iOS 13 中
The default modal presentation style is a card.默认的模态呈现样式是卡片。 This shows the previous view controller at the top and allows the user to swipe away the presented view controller.
这在顶部显示了之前的视图控制器,并允许用户滑动显示的视图控制器。
To retain the old style you need to modify the view controller inside of your button's action method like this:要保留旧样式,您需要像这样修改按钮操作方法中的视图控制器:
secondVc.modalPresentationStyle = .fullScreen
This is the same for both programmatically created and storyboard created controllers.这对于以编程方式创建的和故事板创建的控制器都是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.