How to automatically generate methods like ViewDidLoad

倾然丶 夕夏残阳落幕 提交于 2020-01-24 13:21:31

问题


I want to create a custom class that extends uiviewcontroller with a function that when I create a subClass of my custom class, that function generate automatically. like viewDidLoad and didReceiveMemoryWarning in subclasses of UIViewController. what can I do?

My CustomViewController :

class CustomViewController: UIViewController

My subclass of CustomViewController :

class MySubClass: CustomViewController {

   override func generatedFunction() {

       //Do something
   }
}

回答1:


  • Use code snippets.
  • Go to /Applications/Xcode/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates and edit the templates.



回答2:


You can create a CustomViewController and then add your method to it and then call the method in the viewDidLoad. Like this

import UIKit

class CustomViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.generatedFunction()
    }

    public func generatedFunction() {
        //Do something
    }
}

Then you can use it like this,

import UIKit

class ViewController: CustomViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func generatedFunction() {
        super.generatedFunction()

        // Do Something
    }
}

You need to make sure that if you override viewDidLoad, then you need to call super.viewDidLoad() in it.



来源:https://stackoverflow.com/questions/40138385/how-to-automatically-generate-methods-like-viewdidload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!