我想知道将数据从模型传递到控制器时的最佳做法是什么。
我想做什么
我想在时间改变时更新标签。
CurrentTime.swift(模型)
var timer: Timer?
var currentTime: String?
init() {
if timer == nil{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
}
}
@objc private func updateCurrentTime(){
let df = DateFormatter()
df.dateFormat = "HH:mm"
df.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
}
ViewController.swift
class ViewController: UIViewController {
@IBOutlet var timeLabel: UILabel!
var currentTime = CurrentTime()
override func viewDidLoad() {
}
@IBAction func closeBtnWasPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
答案 0 :(得分:2)
选项1
1-添加此变量
weak var delegate: ViewController?
2在vc的viewDidLoad
中
currentTime.delegate = self
3-
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
delegate?.update(currentTime)
4-在vc内
func update(_ data:String) {
lbl.text = data
}
当然可以的
delegate?.lbl.text = currentTime
但上面是MVC
选项2
var ob:NSKeyValueObservation!
和viewDidLoad
ob = currentTime.observe(\CurrentTime.currentTime, options: .new) { cur, tex in
timeLabel.text = tex
}
答案 1 :(得分:1)
您应定义一个动态类,如下所示:
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
yourGoToBackgroundFunction()
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
yourSaveDataFunction()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
yourSaveDataFunction()
}
}
在模型中,如下更改currentTime属性的定义:
class Dynamic<T> {
var bind: (T) -> Void = { _ in }
var value: T? {
didSet {
bind(value!)
}
}
init(_ v: T) {
value = v
}
}
在控制器的viewDidLoad方法中添加以下代码:
var currentTime: Dynamic<String>