尝试从另一个视图控制器调用函数时出错

时间:2015-10-14 21:24:43

标签: ios swift

我有两个视图控制器,想要从第二个视图控制器中调用一个函数。

这有效:

class ViewControllerOne: UIViewController {

    func doSomething() {
        print("Did something")
    }

}

class ViewControllerTwo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad() 
        let vcOne: ViewControllerOne = ViewControllerOne()
        vcOne.doSomething()
    }

}

但是当我在self.ScrollView.setContentOffset(...)函数中ScrollViewIBOutlet ViewControllerOne doSomething()}时,我尽快得到Unexpectedly found nil while unwrapping an optional value.该函数从ViewControllerTwo调用。如果有人可以解释我做错了什么以及可能如何修复它会很好。

导致错误的实际代码:

class PageContainerViewController: UIViewController {
    @IBOutlet weak var ScrollView: UIScrollView!
    ...
    func setOffset() {
        self.ScrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    }
    ...
}

class ContactsTableViewController: UITableViewController {
    ...
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let selected = __contacts[indexPath.row]
        if !__chats.contains(selected) {
            __chats.append(selected)
            let pageContainer: PageContainerViewController = PageContainerViewController()
            pageContainer.setOffset()

        }

        activeChat = selected

        print(__chats)
    }
    ...
}

1 个答案:

答案 0 :(得分:0)

好的,这就是你必须要做的,基于这个样本,这就是:

第一个ViewController的代码:

import UIKit
public class ViewController: UIViewController {

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

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

  public func DoSomething(parameter: String) ->String{
      return parameter
  }
  }

这是第二个ViewController的代码:

import UIKit

class ViewController2: UIViewController {

    @IBOutlet var labelParameter: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        let controller: ViewController = ViewController()

        labelParameter.text = controller.DoSomething("Test")

        // Do any additional setup after loading the view.
    }

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


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

我认为故事板无关紧要,但如果您需要,请告诉我;从技术上讲,我有第一个带有按钮的视图控制器,按钮有一个segue,第二个视图控制器从第一个DoSomething调用ViewController方法。

我希望这是你正在寻找的想法。