问题描述
我的项目在应用程序的每个屏幕上都有一个自定义选项卡,因此我制作了自定义的 UIView
类和 xib
文件,并在其中添加了按钮.现在,我想要在具有不同故事板
id的不同屏幕上导航的按钮.但是我不能从 UIView
类调用 presentViewController
.以前,我在 extension
类中自定义函数以在屏幕之间导航,但是 UIView
类也无法调用该函数.
There is a custom tab in in my project that is on every screen of the app, so i made custom UIView
class and xib
file and added buttons in them. Now i want my buttons for navigations on different screens having different story board
ids. But i can't call presentViewController
from UIView
class. Previously i custom function in extension
class to navigate between screens but UIView
class also can't call that function.
import UIKit
@IBDesignable class tab: UIView {
var view: UIView!
@IBAction func btn1(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("6")
self.presentViewController(vc, animated: true, completion: nil)
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "tab", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
推荐答案
在按钮上调用此函数
func infoClick() {
let storyboard: UIStoryboard = UIStoryboard (name: "Main", bundle: nil)
let vc: CampainDetailView = storyboard.instantiateViewControllerWithIdentifier("campainDetailView") as! CampainDetailView
let currentController = self.getCurrentViewController()
currentController?.presentViewController(vc, animated: false, completion: nil)
}
此功能将创建根视图控制器
This function will create root view controller
func getCurrentViewController() -> UIViewController? {
if let rootController = UIApplication.shared.keyWindow?.rootViewController {
var currentController: UIViewController! = rootController
while( currentController.presentedViewController != nil ) {
currentController = currentController.presentedViewController
}
return currentController
}
return nil
}
上面的代码必须有效,它在 Swift 4.0
This above code must work, it is working for me in Swift 4.0
这篇关于如何在UIView类中调用presentViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!