ios - 在所有 viewDidLoad 函数中重复相同的语句可能的扩展文件

标签 ios swift function loops extension-methods

我希望在我所有项目的 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/

相关文章:

ios - Obj-C 中的 3D Touch Home 快捷方式

ios - 从 AVAudioRecorder 获取分贝

ios - 访问旧版本网站的 URLSession 数据任务?

swift - 检测 UITextView 何时被编辑

php - 为什么我的变量通过引用传递?

php:将数字转换为字母,反之亦然

ios - 使用默认值初始化 ViewModel

即使没有碰撞位掩码,swift skspritenode 也会发生碰撞

ios - UITextField 清除按钮位置不正确

c - 怪异的迪基文件