【问题标题】:How do I call a method from another class in Swift?如何在 Swift 中调用另一个类的方法?
【发布时间】:2015-06-22 02:43:05
【问题描述】:

当在 FirstViewController 中按下按钮时,我希望它在另一个类 (SecondViewController) 中调用 funcpressedButton()。我该怎么做?

我尝试了以下方法,但它不能正常工作:

SecondViewController().pressedButton()

这里是pressedButton的代码:

func pressLearnButton() {
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        self.scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: true)
    }

【问题讨论】:

  • 您能否更具体地说明您要实施的内容?它可能有助于回答您的问题。例如,您是否使用 segue 在 FirstViewController (FVC) 和 SVC 之间进行切换?还是 SVC 存在于 FVC 中?
  • 这是可能的(下面给出的答案是变通方法,可能有一些优点,但我认为这不是您想要的),但我们必须知道您的视图层次结构才能帮助您. SecondViewControllerFirstViewController 是什么关系?
  • 在我看来,您似乎还不了解面向对象编程的一些概念。这还不错,每个人都从某个地方开始。我建议您阅读 OOP 的基础知识,以了解类和对象之间的区别,如何引用其他对象并向它们发送消息。
  • 您没有提供足够的信息。 FirstViewController 的实例是如何出现在屏幕上的?屏幕上是否已经存在 SecondViewController 的实例(可能在导航控制器堆栈的更下方,或者从 SecondViewController 的实例到 FirstViewController 的实例的模态presentViewController:animated:completion:?)或者您是否需要创建 SecondViewController 的新实例?
  • 在故事板上,所有的视图都没有连接。 SecondViewController 有一个 UIScrollView,我在其中将 FirstViewController 和其他人添加到它的子视图中。我正在尝试在 FirstViewController (滚动视图的第一个控制器)上按下一个按钮,使滚动视图移动到某个偏移量。滚动视图在 SecondViewController 中。

标签: ios class swift


【解决方案1】:

从句法上讲,您似乎正在尝试完成 静态方法 通常所做的事情。除非这是你想要完成的,我猜it's not,你需要在调用方法之前实例化你的 SecondViewController,将它分配给一个变量,然后调用你想要的方法,如下所示:

let otherViewController: SecondViewController = SecondViewController()
let result = otherViewController.doSomething()

如果您在单击按钮时尝试转换(转场)到另一个视图控制器,您应该使用prepareForSegue() method 来转换到下一个视图控制器。另外,不要忘记在 Storyboard 上设置 segue 标识符。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    首先,您必须在 FirstViewController 中保留对 SecondViewController 实例的引用。然后,为了从您的 FirstViewController 调用 SecondViewController 中的函数 foo(),只需调用 secondInstance.foo()。如果 foo() 是类函数,你可以用SecondViewController.foo().调用

    class A : UIViewController {
        var myB  = B()
    
        func callBFoo() {
            myB.foo()
        }
    
        func callStaticBFoo() {
            B.staticFoo()
        }
    }
    
    class B : UIViewController {
        func foo() {
            println("foo")
        }
    
        class func staticFoo() {
            println("static foo")
        }
    }
    

    【讨论】:

    • 那行不通,因为我需要在 SecondViewController 中使用滚动视图
    • 您说“这不会真正起作用,因为我需要在 SecondViewController 中使用滚动视图”。抱歉,这没有多大意义。
    【解决方案3】:

    你真的叫它。但是,就您而言,这取决于许多因素。似乎它必须通过调用pressedButton 方法来显示任何内容。 需要声明控制器的变量,将其添加到当前控制器的视图中,您将看到可视化数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多