Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在UIViewcontroller扩展中创建公共函数?_Ios_Swift_Swift4 - Fatal编程技术网

Ios 如何在UIViewcontroller扩展中创建公共函数?

Ios 如何在UIViewcontroller扩展中创建公共函数?,ios,swift,swift4,Ios,Swift,Swift4,我需要对所有UIViewcontroller运行公共函数,而无需手动指定self.function重写无法修改的类(如UIViewcontroller基类)中的函数的唯一方法是使用方法swizzling 您可以使用此技术快速切换viewDidLoad或ViewDidDisplay 大多数情况下,您应该根据需要对UIViewController进行子类化,并在lifecycle method override中调用您的函数。只需使用扩展将自定义方法添加到UIViewController: exte

我需要对所有UIViewcontroller运行公共函数,而无需手动指定self.function

重写无法修改的类(如UIViewcontroller基类)中的函数的唯一方法是使用方法swizzling

您可以使用此技术快速切换viewDidLoad或ViewDidDisplay


大多数情况下,您应该根据需要对UIViewController进行子类化,并在lifecycle method override中调用您的函数。

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

extension UIViewController {

   func customFunc() {
      print("Custom func is called")
   }
}
现在,在从UIViewController继承的每个类中,您都可以轻松访问此函数:

class MainVC: UIViewController {

   override func viewDidLoad() {
    super.viewDidLoad()

   //call your func
   customFunc()
   }

}

我认为在swift4中不可能快速加载viewDidload,尽管之前可以通过快速加载来实现,但是您可以通过继承来实现

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 
    }
}

您希望它什么时候运行?需要为加载的每个UIviewcontroller自动运行。但不会指定函数名。创建UIViewController类型的BaseViewController,重写所有需要的行为。然后将所有其他vcs创建为BaseViewController的子类。@Leena让你得到了答案。我想我得到了否决票,因为OP要求不要手动调用该函数,而是在viewDidLoad上自动运行它。很公平。在编写解决方案时,我很可能没有注意到这一细节。哎呀。