我想触摸 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 之前的@IBOutlet。
var myClass : MyClass!
你也可以试试这个:
var myClass : MyClass! = MyClass()
然而,从外观上看,您在 MyClass 的 setFocus() 中所做的一切都可以在 ViewController 中轻松地重新创建。
关于swift - iOS 8 和 swift : call a function in another class from view controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706404/