【问题标题】:How to create a common function in UIViewcontroller extenstion?如何在 UIViewcontroller 扩展中创建通用功能?
【发布时间】:2018-09-15 11:24:43
【问题描述】:

我需要在不手动指定“self.function()”的情况下对所有 UIViewcontroller 运行通用函数

【问题讨论】:

  • 您希望它何时运行?
  • 自动需要为每个加载的 UIviewcontroller 运行。但不会指定函数名称。
  • 创建 UIViewController 类型的 BaseViewController,覆盖所有需要的行为。然后将所有其余的 vcs 创建为 BaseViewController 的子类。

标签: ios swift swift4


【解决方案1】:

我认为在 swift4 中无法对 viewDidload() 进行 swizzle,尽管之前可以通过 swizzling 来实现,但您可以通过继承来实现

Class BaseVC: UIViewController {
    func viewDidLoad() {
    super.viewDidLoad() 
  /// customization here … e.g self.function() 
    }
}

Class CustomVC: BaseVC {
 func viewDidLoad() {
    super.viewDidLoad() 
     // you had called self.function no need to do it again 
    }
}

【讨论】:

  • @Leena 你得到了答案。
【解决方案2】:

只需使用扩展将您的自定义方法添加到 UIViewController:

extension UIViewController {

   func customFunc() {
      print("Custom func is called")
   }
}

现在,在从 UIViewController 继承的每个类中,您都可以轻松访问此函数:

class MainVC: UIViewController {

   override func viewDidLoad() {
    super.viewDidLoad()

   //call your func
   customFunc()
   }

}

【讨论】:

  • 我猜我投了反对票,因为 OP 要求不要手动调用该函数,而是在 viewDidLoad() 中自动运行它。很公平。很可能在编写解决方案时我没有注意到这一细节。哎呀。
【解决方案3】:

在您无法修改的类(例如UIViewController 基类)中覆盖函数的唯一方法是使用方法调配。

How to swizzle init in Swift

您可以使用此技术来调配viewDidLoadviewDidAppear

不过,大多数时候,您应该只根据需要子类化 UIViewController,并在生命周期方法覆盖中调用您的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多