【问题标题】:ios 8 and Swift: call a function in another class from view controllerios 8 和 Swift:从视图控制器调用另一个类中的函数
【发布时间】:2015-07-29 16:43:43
【问题描述】:

我想在 ViewController 中触摸一个按钮并在自定义类中运行一个简单的函数。不需要参数。代码基本上是:

class MyClass: UIView {
   //init function is here
   //other setup stuff
   ...

func SetFocus() {
//I want to set the camera focus to infinity.
    var error: NSErrorPointer = nil
    var pos: CFloat = 1.0
    captureDevice!.lockForConfiguration(error)
    captureDevice!.setFocusModeLockedWithLensPosition(pos, completionHandler: nil)
    captureDevice!.unlockForConfiguration()
}

}

and in ViewController

import UIKit

class ViewController: UIViewController {

    @IBOutlet var myClass: MyClass!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func myButton(sender: UIButton) {

         myClass.SetFocus()

    }
}

我已经尝试了所有我能想到的东西(Swift 的新功能),但应用程序要么崩溃,要么我调用的函数无法运行。 MyClass 中的其他一切工作正常。

【问题讨论】:

  • myClass 设置在哪里?拨打MyFunction时是否存在?
  • 如果是IBOutlet,您是否已将其连接到 Storyboard 中?
  • 能否在myFunction()中查看具体代码
  • 你也可以使用 NSNotificationCenter 来解决这个问题

标签: swift ios8


【解决方案1】:

尝试从 MyClass 之前删除 @IBOutlet。

var myClass : MyClass!

你也可以试试这个:

var myClass : MyClass! = MyClass()

然而,从外观上看,您在 MyClass 的 setFocus() 中所做的一切,都可以轻松地在 ViewController 中重新创建。

【讨论】:

  • 将 func + 支持代码移动到 ViewController 是关键。非常感谢!
【解决方案2】:

试试这个

 @IBAction func myButton(sender: UIButton) {

    var ClassViewController = self.storyboard.instantiateViewControllerWithIdentifier("StoryboardID") as! UIViewController
ClassViewController.MyFunction()

    }

【讨论】:

  • 谢谢。我按原样尝试了此方法并进行了一些变化-没有成功。
  • 你是否设置了故事板 ID
猜你喜欢
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2017-03-23
  • 1970-01-01
  • 2020-09-06
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多