gpt4 book ai didi

ios - 如何在快速点击按钮时从第二个 View Controller 调用第一个 View Controller 功能?

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

我有一个要求,我必须在点击按钮时从第二个 View Controller 调用第一个 View Controller 函数。

class FirstViewController: UIViewController {

@IBAction func firstButtonPressed(_ sender: Any) {
// Doing ABC
}

@IBAction func showSecondVC_ sender: Any) {
// showingSecondVC
}

}

class secondViewController: UIViewController {
@IBAction func SecondButtonPressed(_ sender: Any)
// Dismiss second vc & call First View controller method so that it does ABC.
}

我的第一个问题是我们可以直接从第二个 VC 启动第一个 VC IBAction 吗?可能吗?

我正在考虑做以下事情

class FirstViewController: UIViewController {

@IBAction func firstButtonPressed(_ sender: Any) {
// call DoABC
}

func DoABC {
// Doing ABC
}

}

class secondViewController: UIViewController {
@IBAction func SecondButtonPressed(_ sender: Any)
// Dismiss second vc
// Call Firstvc.DoABC ?? How to do this ??
}

如何从第二个vc调用第一个vc方法??

最佳答案

这里有几个选项:

  1. 拆分逻辑,从每个 View Controller 调用相同的代码
  2. 使用闭包回调
  3. 使用委托(delegate)模式作为回调方法

选项 1 - 拆分逻辑:

class FirstViewController: UIViewController {

let abcPerformer = ABCPerformer()

@IBAction func firstButtonPressed(_ sender: Any) {
abcPerformer.doABC()
}

@IBAction func showSecondVC_ sender: Any) {
// showingSecondVC
}

}

class SecondViewController: UIViewController {

let abcPerformer = ABCPerformer()

@IBAction func SecondButtonPressed(_ sender: Any) {
// Dismiss second vc & call First View controller method so that it does ABC.
abcPerformer.doABC()
}

}

struct ABCPerformer {

func doABC() {
// do ABC
}

}

选项 2 - 创建回调:

class FirstViewController: UIViewController {

@IBAction func firstButtonPressed(_ sender: Any) {
doABC()
}

@IBAction func showSecondVC_ sender: Any) {
// showingSecondVC
secondVC.doABC = doABC
}

func doABC() {
// do ABC
}

}

class SecondViewController: UIViewController {

var doABC: (() -> Void)?

@IBAction func SecondButtonPressed(_ sender: Any) {
// Dismiss second vc & call First View controller method so that it does ABC.
doABC?()
}

}

选项 3 - 使用代理:

protocol ABCProtocol {
func doABC()
}

class FirstViewController: UIViewController, ABCProtocol {

@IBAction func firstButtonPressed(_ sender: Any) {
doABC()
}

@IBAction func showSecondVC_ sender: Any) {
// showingSecondVC
secondVC.delegate = self
}

func doABC() {
// do ABC
}

}

class SecondViewController: UIViewController {

weak var delegate: ABCProtocol?

@IBAction func SecondButtonPressed(_ sender: Any) {
// Dismiss second vc & call First View controller method so that it does ABC.
delegate?.doABC()
}

}

可能还有更多选择,但这些应该给你足够的选择来做出决定

关于ios - 如何在快速点击按钮时从第二个 View Controller 调用第一个 View Controller 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507479/

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