iOS swift,在UIView中调用touchesEnded时,storyboard中的presencetViewController其他xib或ViewController

标签 ios swift uiview uiviewcontroller presentviewcontroller

我想在 xib 中调用 touchedEnded 函数时呈现 ViewController,但我不知道如何实现它。

这是我项目的一部分。

//ViewController.swift

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // add custom xib view (day view)
        let view = Bundle.main.loadNibNamed("ScheduleView", owner: self, options: nil)?.first as! ScheduleView
        view.frame = self.view.frame

        self.view.addSubview(view)
    }


}

//ScheduleView.swift

class ScheduleView.swift: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        print("touchesBegan")
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)

        print("touchesEnd")

        // move scene in here
        // show secondViewController
    }



}

//secondeViewController.swift

class secondeViewController.swift: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

    }


}

最佳答案

只有 View Controller 可以呈现另一个 View Controller 。 您可以使用委托(delegate)模式来做到这一点。

创建新协议(protocol)

protocol PresentVCDelegate {
    func presentVC()
}

在 ScheduleView 中添加一个属性

var presentVCDelegate: PresentVCDelegate

在您的 ViewController 中,遵守此协议(protocol)并将 View 的委托(delegate)设置为 self

//in view will appear
view.presentVCDelegate = self

不要忘记遵守协议(protocol)

extension ViewController: PresentVCDelegate {
    func presentVC() {
        //present your secondViewController here
    }
}

最后在 ScheduleView 的 touchEnd 方法中,调用委托(delegate)方法

self.presentVCDelegate.presentVC()

关于iOS swift,在UIView中调用touchesEnded时,storyboard中的presencetViewController其他xib或ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47077546/

相关文章:

ios - 如何淡化 UIView 背景颜色 - iOS 5

ios - 定时器后开始 Action

ios - Swift 中 UIViewController 所需的构造函数

ios - 以非编程方式使用 (UIView) 类 - Swift

ios - 横向和纵向的动态角半径

ios - 是否显示 UIView?

ios - 选择允许外部存储时,iPhone 核心数据迁移导致二进制数据丢失

ios - 呈现新的 ViewController 后 Deinit UITabBarController

arrays - 为什么我不能将元素附加到结构?

ios - 使用 Quartz 2D 在上下文中垂直居中文本