调整UINavigationController

时间:2016-01-07 17:48:55

标签: ios swift

在我的每个视图控制器中,我都调用一个编辑导航控制器外观和左/右按钮文本的功能。我没有在每个视图控制器中都有这个代码,而是试图实现每个视图控制器符合的协议。

每个视图控制器中的当前代码:

func setupNavReg(backButtonText: String, nextButtonText: String)
{
    self.navigationController!.navigationBar.barTintColor = UIColor.whiteColor()
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)

    let leftNavButton = UIBarButtonItem(title: backButtonText, style: .Plain, target: self, action: Selector("backButtonPressed"))
    let customFont = UIFont(name: "Gill Sans", size: 14.0)

    leftNavButton.setTitleTextAttributes([NSFontAttributeName:customFont!], forState: UIControlState.Normal)
    self.navigationItem.leftBarButtonItem = leftNavButton

    //nextButton left out for     
}

协议设计

protocol navBarInterface {
    var navigationController: UINavigationController? { get }
    func configureWithBackButton(backButtonText: String, nextButtonText: String)
}

extension navBarInterface {
    func configureWithBackButton(backButtonText: String, nextButtonText: String) {

    if let navigationController = navigationController {
        navigationController.navigationBar.barTintColor = UIColor.whiteColor()
        navigationController.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
        navigationController.navigationBar.shadowImage = UIImage()
        let customFont = UIFont(name: "Gill Sans", size: 14.0)

        let leftNavButton = UIBarButtonItem(title: backButtonText, style: .Plain, target: nil, action: Selector("backButtonPressed"))
        leftNavButton.tintColor = UIColor.whiteColor()
        leftNavButton.setTitleTextAttributes([NSFontAttributeName:customFont!], forState: UIControlState.Normal)
        navigationController.navigationItem.leftBarButtonItem = leftNavButton  

        //nextButton left out 
        }
    }
}

到目前为止,我无法让它发挥作用。导航控制器的外观并没有改变,但我发现当视图控制器出现时,我设置的协议断点正在被击中。我也担心在按下导航按钮时我无法点击选择器功能。

1 个答案:

答案 0 :(得分:0)

如果此协议仅适用于UINavigationController,那么我会忘记协议,只需在extension UINavigationController { func configureWithBackButton(backButtonText: String, nextButtonText: String) { self.navigationBar.barTintColor = UIColor.whiteColor() self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) self.navigationBar.shadowImage = UIImage() let customFont = UIFont(name: "Gill Sans", size: 14.0) let leftNavButton = UIBarButtonItem(title: "Back", style: .Plain, target: nil, action: Selector("backButtonPressed")) leftNavButton.tintColor = UIColor.whiteColor() leftNavButton.setTitleTextAttributes([NSFontAttributeName:customFont!], forState: UIControlState.Normal) self.navigationItem.leftBarButtonItem = leftNavButton //nextButton left out } } 上定义扩展名:

setupNavReg

我只是说因为协议有时会以类和子类的时髦方式进行交互 - 也就是说,如果你的类定义了方法会发生什么,但是协议也定义了它,等等。所以尝试扩展类,看看是否解决了问题。

我还注意到您的代码不同 - 在原始方法backButtonText中,您将后退按钮的文本设置为"Back",但在您的扩展程序中,您将其设置为group(2) }。这是故意的吗?这可能就是为什么文本没有改变为你传递给方法的任何字符串...