【问题标题】:Save actions on previous ViewController在以前的 ViewController 上保存操作
【发布时间】:2022-01-23 17:20:39
【问题描述】:

我的主屏幕上只有一个按钮“显示下一个屏幕”。当第二个屏幕(VC)弹出时,它有2个按钮(返回和toSelect按钮)。

我的目标是当我显示第二个屏幕并在其上选择一个按钮然后返回到第一个屏幕时。我的第二个屏幕上的按钮将保持选中状态。我该怎么做?

所以基本上我需要在第二个屏幕上保存我的操作,所以如果我回到它,它会显示我所做的一切。

最好的方法是什么?

Storyboard

【问题讨论】:

标签: ios swift delegates storyboard


【解决方案1】:

使用委托和协议实现此目的的最简单方法。

您应该使用委托方法在 FirstViewController 处监听并保存 SecondViewController 的更改。

当您展示 secondViewController 时,您会将保存的更改分享给 secondViewController,以便可以代表该信息选择按钮

代码-

class FirstViewController: UIViewController {
    
    //secondViewController States
    private var isButtonSelected = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func gotoSecondVCAction(_ sender: Any) {
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        guard let secondVC = storyBoard.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController else { return }
        secondVC.isButtonSelected = isButtonSelected
        secondVC.delegate = self
        self.present(secondVC, animated: true, completion: nil)
    }


}

extension FirstViewController: ButtonSelectionProtocol {
    func button(isSelected: Bool) {
        isButtonSelected = isSelected
    }
}

对于 secondViewController

protocol ButtonSelectionProtocol {
    func button(isSelected:Bool)
}

class SecondViewController: UIViewController {
    var isButtonSelected : Bool = false
    var delegate:ButtonSelectionProtocol?
    
    @IBOutlet weak var selectButton: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if isButtonSelected {
            selectButton.tintColor = .red
            selectButton.setTitle("Selected", for: .normal)
        }else{
            selectButton.tintColor = .green
            selectButton.setTitle("Select Me", for: .normal)
        }
    }
    
    
    @IBAction func gobackAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    @IBAction func selectAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
        isButtonSelected.toggle()
        delegate?.button(isSelected: isButtonSelected)
    }
}

【讨论】:

  • 在 Swift 中 使用 回调闭包 甚至 presentingController 属性实现此目的的最简单方法。 Objective-C 继承的协议/委托比较麻烦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多