我有两个ViewControllers。在VC1上我有搜索条件,在VC2上我有搜索结果。如果您想从VC2转到VC1,VC2将被关闭。
在VC1上,我有一个NSButton(样式检查,类型切换),默认情况下,我希望它处于打开状态。NSButton的目的是在结果中包含照片。
如果用户取消选中该按钮并按下search,它将转到VC2,显示没有照片的搜索结果。
但是当用户返回VC1进行新的搜索时,就会出现不想要的行为: NSButton是未选中的(我希望每次用户在VC1时都默认选中它。此外,该按钮为nil。
为什么会发生这种情况,我如何才能使它成为每次VC2关闭时都要勾选的按钮框?
我尝试启用它并将其设置为ONState,但由于其为nil,它将崩溃。
发布于 2017-07-04 11:21:49
我已经设法让它以我想要的方式运行,方法是添加
switch.state=1就在执行从VC1到VC2的分段之前。
然而,我不认为这是最优雅的解决方案,因为按钮仍然是空的。
更新:我发现这个问题是因为当它从VC1转到VC2时,VC1变成了nil,当VC2被忽略时,它也变成了nil。因此才会发生崩溃。一种解决方案是使用委托。
VC1:
class FirstViewController: UIViewController,SecondViewControllerProtocol {
@IBOutlet var firstName: UITextField!
@IBOutlet var lastName: UITextField!
@IBOutlet var subscribeSwitch: UISwitch!
@IBAction func goToSecondVC(_ sender: Any) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: SecondViewController.self)) as! SecondViewController
viewController.delegate = self
self.present(viewController, animated: true, completion: nil)
}
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.
}
func dismissViewController() {
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController"){
subscribeSwitch.isOn=true
}
}
}VC2:
protocol SecondViewControllerProtocol {
func dismissViewController()
}
class SecondViewController: UIViewController {
var delegate:SecondViewControllerProtocol!
@IBAction func goBackToFirstVC(_ sender: Any) {
self.dismiss(animated: true) {
self.delegate!.dismissViewController()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}发布于 2017-07-08 00:17:25
若要在每次打开控制器时设置状态,请使用
-(void)viewWillAppear要让viewControllers彼此通信,您可以实现委托。这里有一个非常好的教程:Link
另一种方法是使用Notifications -> Link进行通信
或者,您可以在像prepareForSegue这样的方法上设置值-这取决于您用来初始化控制器的内容。
https://stackoverflow.com/questions/44895520
复制相似问题