gpt4 book ai didi

ios - 尝试从另一个 View Controller 调用函数时出错

转载 作者:搜寻专家 更新时间:2023-11-01 05:38:59 25 4
gpt4 key购买 nike

我有两个 View Controller ,想在第二个 View Controller 中调用第一个 View Controller 的函数。

这个有效:

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)
}
...
}

最佳答案

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

第一个 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.
}
*/

}

我认为 Storyboard无关紧要,但如果您需要,请告诉我;从技术上讲,我有第一个带有按钮的 View Controller ,该按钮有一个 segue,第二个 View Controller 从第一个 ViewController 调用 DoSomething 方法。

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

关于ios - 尝试从另一个 View Controller 调用函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com