Iva*_*hin 5 uiviewcontroller ios swift
假设我有一个 firstViewController 和一个 secondViewController。第一个包含一个 firstButton,第二个包含一个 secondButton。这是我想要做的:当用户单击 secondButton 时,一些 firstButton 的属性会发生变化。
不幸的是,当我在 secondViewController 中创建 firstViewController 的实例然后尝试访问 firstButton 时,出现错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
Run Code Online (Sandbox Code Playgroud)
因此,从技术上讲,我正在尝试按以下方式执行此操作:
var ins = firstViewController()
@IBAction func secondButtonisPressed(){
ins.firstButton.alpha = 0
}
Run Code Online (Sandbox Code Playgroud)
实现它的正确方法是什么?
提前致谢。
这里的问题是,只有在调用 s 方法之后,IBOutlets您的firstViewController才可用 ( != nil) 。viewDidLoad() firstViewController
换句话说,您必须先呈现视图,然后才能对UIViewController IBOutlet.
你如何解决这个问题?
添加一个变量FirstViewController作为您的标志。
例如:var hideFirstButton = false
在viewDidLoad或viewWillAppear方法中FirstViewController检查 的hideFirstButton值并隐藏或显示您的firstButton.
然后,在提交之前,FirstViewController将 的值更改hideFirstButton为应用程序正常运行所需的值。
更新:
使用Storyboard 的其他解决方法是(此方法的不便之处在于,在viewWillAppear() 之后调用完成处理程序,因此按钮会显示一秒钟):
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
self.presentViewController(firstViewController, animated: true, completion: {
//This lines will be called after the view is loaded so the code will run
firstViewController.firstButton.alpha = 0
})
Run Code Online (Sandbox Code Playgroud)
示例: GitHub 上的示例
| 归档时间: |
|
| 查看次数: |
5519 次 |
| 最近记录: |