如何在UIView类中调用presentViewController?

时间:2016-01-07 07:04:17

标签: ios swift uiview presentviewcontroller

我的项目中有一个自定义标签位于应用的每个屏幕上,因此我制作了自定义UIView类和xib文件,并在其中添加了按钮。现在我希望我的按钮在不同屏幕上的导航具有不同的story board ID。但我无法从presentViewController课程中拨打UIView。以前我在extension课程中自定义功能以在屏幕之间导航,但UIView课程也无法调用该功能。

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

3 个答案:

答案 0 :(得分:7)

在按钮上调用此功能

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)

    }

此功能将创建根视图控制器

func getCurrentViewController() -> UIViewController? {

    if let rootController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        var currentController: UIViewController! = rootController
        while( currentController.presentedViewController != nil ) {
            currentController = currentController.presentedViewController
        }
        return currentController
    }
    return nil

}

以上代码必须正常工作,它适用于 Swift 2.1

答案 1 :(得分:4)

您可以使用委托。将其添加到Tab类

protocol TabDelegate {

    func didButtonTapped()
}

var delegate: TabDelegate?

@IBAction func btn1(sender: UIButton) {
    delegate?.didButtonTapped()
}

在viewController中使用Tab。 像这样设置委托

let tab = Tab()
tab.delegate = self

然后在委托方法中推送新的viewController 并且您可以使BaseViewController执行此操作,然后所有viewController子类都可以具有相同的功能。

class BaseViewController: UIViewController, TabDelegate {

    func didButtonTapped() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("6")
        self.presentViewController(vc, animated: true, completion: nil)
    }
}

Class ViewControllerA: BaseViewController {
}

Class ViewControllerB: BaseViewController {
}

答案 2 :(得分:0)

向此类添加属性,然后您可以使用控制器的方法。

弱var控制器:UIViewController!

self.controller?.presentViewController(vc,animated:true,completion:nil)