ios 8 和 Swift:从视图控制器调用另一个 class 中的函数

ios 8 and Swift: call a function in another class from view controller

我想触摸 ViewController 中的按钮和 运行 自定义 class 中的简单功能。不需要参数。代码基本上是:

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 中的其他一切正常。

试试这个

 @IBAction func myButton(sender: UIButton) {

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

    }

尝试删除MyClass之前的@IBOutlet。

var myClass : MyClass!

你也可以试试这个:

var myClass : MyClass! = MyClass()

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