代码之家  ›  专栏  ›  技术社区  ›  Benjamin RD

使用Swift实现所有UIViewController的功能

  •  1
  • Benjamin RD  · 技术社区  · 8 年前

    是否有方法实现所有 UIViewControllers ?

    我试图为所有UIViewController扩展一个特定的行为,这是非常标准的。

    例如:

    MyBaseClass

    class MyBaseClass {
        public func load(viewController:UIViewController){
            print("The size of the view is \(viewController.view.size.width)")
        }
    }
    

    我必须在100人中实施类似的行为 UIViewController

    2 回复  |  直到 8 年前
        1
  •  1
  •   picciano    8 年前

    一种方法是将协议与 UIViewController

    将您的行为定义为协议并扩展 UIViewController 要实施它:

    protocol WidthProtocol {
    
        func showWidth()
    
    }
    
    extension UIViewController: WidthProtocol {
    
        func showWidth() {
            print("The width of the view is \(self.view.frame.size.width)")
        }
    
    }
    

    一旦有了它,就可以从 UIViewController ,例如:

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Show the width
            showWidth()
        }
    
    }
    
        2
  •  1
  •   RomOne    8 年前

    或者,如果您不想在所有视图控制器中调用相同的函数,可以将其子类化:

    class YourCustomViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            print("The size of the view is \(view.frame.width)")
        }
    
    }
    

    那就换一个 UIViewController 通过 YourCustomViewController :

    class oneOfYour100Controler : UIViewController {
    

    比如:

    class oneOfYour100Controler : YourCustomViewController {
    

    然后,您无需执行任何操作,消息将自动打印。