代码之家  ›  专栏  ›  技术社区  ›  sk123

如何在swift中将函数从扩展名调用到uiviewcontroller

  •  2
  • sk123  · 技术社区  · 7 年前

    我想让我 Navigation bar 透明。当我在同一个 ViewController 但是我想在其他许多地方重用它 ViewControllers 所以我决定用 extension 扩展 UINavigationController . 当我尝试将函数调用为 ViewDidLoad ,不起作用。

    import UIKit
    
    class StudentsViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.navigationController?.makeNavigationBarTransparent()   
        } 
    }
    

    这是我的分机

    import UIKit
    
    extension UINavigationController {
        func makeNavigationBarTransparent() {
            navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
            navigationController?.navigationBar.shadowImage = UIImage()
        }
    }
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Ashley Mills    7 年前

    你不需要上的 navigationController?.

    extension UINavigationController {
        func makeNavigationBarTransparent() {
            navigationBar.setBackgroundImage(UIImage(), for: .default)
            navigationBar.shadowImage = UIImage()
        }
    }
    
        2
  •  2
  •   Å těpán    7 年前

    由于您决定编写导航控制器的扩展名,因此必须从它的预测中编写它:

    import UIKit
    
    extension UINavigationController {
        func makeNavigationBarTransparent() {
            self.navigationBar.setBackgroundImage(UIImage(), for: .default)
            self.navigationBar.shadowImage = UIImage()
        }
    }
    
        3
  •  1
  •   U. Benlice    7 年前

    这是因为你的视图控制器还没有放到你的导航堆栈中。如果您的vc未放置在导航堆栈中,则self.navigationcontroller将返回 .

    尝试移动您的 生成导航BarTransparent() 呼叫 将显示视图 方法。