swift - iOS 8 和 swift : call a function in another class from view controller

标签 swift ios8

我想触摸 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/

相关文章:

swift - Alamofire 照片上传,正文中包含文件 key

ios - 如何使用带有 swift 的 API 点唱机在应用程序上流式传输音乐?

ios - 在单个标签中使用多种字体颜色

objective-c - iOS 8 快照尚未呈现的 View 会导致空快照

ios - 将 NSDate 转换为 NSString 并返回不会返回相同的日期

swift - 开关 : Enum Switch issue : Not member of a int

ios - 使 UISearchBar 像音乐应用程序一样关闭

ios - 是否可以在 iOS 交互式通知中显示操作按钮?

iOS8 Touch ID 获取错误 : Pending UI mechanism already set

ios - CloudKit - 如果记录不存在如何保存