这个问题的答案可能是显而易见的,但我想知道是否有可能在 View Controller 被 segued 到 X 次之后创建一个事件,例如警报或弹出窗口,例如第三次加载 View Controller 时出现弹出窗口,因为我似乎无法在网上找到任何相关信息。
该事件应该是一次性发生的,一旦触发就不应再次发生。
最佳答案
这是一些示例代码,您如何使用 NSUserDefaults
来执行您描述的操作。
您需要通过标识符存储在 NSUserDefaults
中的值,最简单的方法是作为一个整数
。
每当您调用 increaseViewLoadedCount()
时,它都会增加计数器的值,例如已加载 View 。
每当您调用 shouldShowAlert()
时,我们都会从默认值中读取值,将其与某个值进行检查,并返回一个基于该值的 boolean
。
此外,NSUserdefaults
正在同步,因此即使应用程序终止,计数器值也会保留。
extension UserDefaults {
/// Indetifier of counter container in `defaults`
private static let kCounterIdentifier = "counter"
/// Count of loads after the alert should not be loaded
private static let notDisplayAlertAfterCount = 3
/// Increase the counter value
func increaseViewLoadedCount() {
guard let counterValue = value(forKey: UserDefaults.kCounterIdentifier) as? Int else {
syncronizeCounter(with: 1)
return
}
syncronizeCounter(with: counterValue + 1)
}
/// Reset the value to zero in Userdaults
func resetViewLoadedCount() {
syncronizeCounter(with: 0)
}
/// Check weather the alert should be presented or not
///
/// - Returns: true if counter is smaller than notDisplayAlertAfterCount, false if greater
func shouldShowAlert() -> Bool {
guard let counterValue = value(forKey: UserDefaults.kCounterIdentifier) as? Int else {
return true
}
// Set the number anything you like
return counterValue < UserDefaults.notDisplayAlertAfterCount ? true : false
}
private func syncronizeCounter(with value: Int) {
set(value, forKey: UserDefaults.kCounterIdentifier)
synchronize()
}
}
测试:
print(defaults.shouldShowAlert()) // prints true
defaults.increaseViewLoadedCount()
defaults.increaseViewLoadedCount()
print(defaults.shouldShowAlert()) // prints true
defaults.increaseViewLoadedCount()
print(defaults.shouldShowAlert()) // prints false
关于ios - Swift:如何在加载 View Controller X 次后创建事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41364327/