gpt4 book ai didi

swift 如何从第二个 vai 协议(protocol)和委托(delegate)模式中的逻辑更新第一个 Controller ?

转载 作者:行者123 更新时间:2023-11-30 10:57:23 25 4
gpt4 key购买 nike

我在第一个 View Controller ViewController 中有一个标签,并且在第二个 vc 中有一个获取日期的函数。我想在第二个定时器启动后更新第一个标签。使用协议(protocol)委托(delegate)模式好吗?此时它不起作用,时间在流逝,但没有更新第一个 VC 中的 View

我的协议(protocol)结构

protocol ViewControllerDelegate: class {        
func changeLabelText(textToPass: String)
}

在第一个 View Controller 中

class ViewController: UIViewController, ViewControllerDelegate {


@IBOutlet weak var mainLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
}


func changeLabelText(textToPass: String) {
self.mainLabel.text = textToPass
self.view.layoutIfNeeded()
}

@IBAction func buttonTapped(_ sender: UIButton) {

let nextVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
nextVC.delegateSubscriber = self
present(nextVC, animated: true, completion: nil)
}

}

在第二个VC中

class SecondViewController: UIViewController {

//MARK: speed timer feature 1/3
private weak var timer: Timer?
private var timerDispatchSourceTimer : DispatchSourceTimer?

weak var delegateSubscriber : ViewControllerDelegate?

@IBOutlet weak var myTxtField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
startTimer(every: 1)
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

print("appeared")
stopTimer()

}

private func startTimer(every timeInterval: TimeInterval) {
if #available(iOS 10.0, *) {
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true) { [weak self] _ in

let dateToPass = Date().description
print(dateToPass)
self?.delegateSubscriber?.changeLabelText(textToPass: dateToPass)

}
}
}

//MARK: speed timer feature 3/3
private func stopTimer() {
timer?.invalidate()
//timerDispatchSourceTimer?.suspend() // if you want to suspend timer
timerDispatchSourceTimer?.cancel()
}

@IBAction func buttonTapped(_ sender: UIButton) {

// delegateSubscriber?.changeLabelText(textToPass: self.myTxtField.text ?? "error")

dismiss(animated: true, completion: nil)
}
}

最佳答案

只需从 Timer 闭包中删除 [weak self]

timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
let dateToPass = Date().description
print(dateToPass)
self.delegateSubscriber?.changeLabelText(textToPass: dateToPass)
}

...那么 self 不是可选的

关于swift 如何从第二个 vai 协议(protocol)和委托(delegate)模式中的逻辑更新第一个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53792680/

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