gpt4 book ai didi

ios - Swift:从另一个 View Controller 调用函数使对象为零

转载 作者:搜寻专家 更新时间:2023-10-31 08:23:00 25 4
gpt4 key购买 nike

我有两个简单的 ViewController:第一个有一个链接到 UIImageView 的 IBOutlet 和一个设置图像 alpha channel 的函数。第二个 Controller 有一个按钮,当它被触发时,应该调用函数来设置 alpha channel 。

这是我的代码:

class FirstViewController: UIViewController {

@IBOutlet imageView: UIImageView!

func changeAlphaChannel() {
imageView.alpha = 0.5
}
}

class SecondViewController: UIViewController {

let firstController = FirstViewController()

@IBAction func buttonPressed(sender: UIButton) {
firstController.changeAlphaChannel()
}
}

在 FirstViewController 中调用 changeAlphaChannel() 以分面方式工作,但如果我按下按钮调用它,imageView 变为 nil 并且应用程序崩溃。我怎样才能解决这个问题?谢谢

最佳答案

它崩溃了,因为你的 imageView 是零。仅使用 FirstViewController() 初始化 firstController 是不行的。您必须从 Storyboard 中加载该 View Controller 。你可以这样做

let storyboard: UIStoryboard = UIStoryboard.init(name: "StoryboardName", bundle: nil)
let firstViewController: FirstViewController = storyboard.instantiateViewControllerWithIdentifier("StoryboardIdentifier") as! FirstViewController

更新

现在只有在实例化 firstViewController 的 View 时才会设置 firstViewController 的 IBOutlets,这在您的情况下不会发生。您要做的是首先显示 firstViewController 的 View ,然后调用您的函数。

关于ios - Swift:从另一个 View Controller 调用函数使对象为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104324/

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