我希望在我所有项目的 viewDidLoad
函数中重复同样的语句。我知道我可以手动输入它,但我正试图找到一种方法来提高我的代码速度。我不知道我是否可以在其中使用扩展文件。
override func viewDidLoad() {
super.viewDidLoad()
let myswitchBoolValuefromFirstVc : Bool = UserDefaults.standard.bool(forKey: "mySwitch")// this is how you retrieve the bool value
// to see the value, just print those with conditions. you can use those for your things.
if myswitchBoolValuefromFirstVc == true {
print("true")
rosaryCounterLabel.isHidden = false
}
else {
print("false")
rosaryCounterLabel.isHidden = true
}
最佳答案
如果您准备滥用 UIViewController 仍在使用的 Objective-C 运行时,您可以使用方法调配来执行您要求的操作。 https://medium.com/@abhimuralidharan/method-swizzling-in-ios-swift-1f38edaf984f
let aClass: AnyClass! = object_getClass(instance)
let originalMethod = class_getInstanceMethod(aClass, #selector(viewDidLoad))
let swizzledMethod = class_getInstanceMethod(aClass, #selector(newViewDidLoad))
if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
但我不推荐它。您在可发现性和重复性之间进行权衡。在您控制所有代码的情况下,使用子类化之类的解决方案将更容易维护,但仍需要在每个 View Controller 中进行一些更改。
关于ios - 在所有 viewDidLoad 函数中重复相同的语句可能的扩展文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245175/