2017-07-16 105 views
0

我有一個BarButtonItem我想添加到我的應用程序中的每個ViewController。我怎樣才能做到這一點,而不必將按鈕創建代碼和動作函數複製/粘貼到每個ViewController中?我更喜歡可重用性,而不是在每個ViewController中都有相同的代碼。Swift 3 - 添加BarButtonItem到NavigationBar在每個ViewController不重複代碼

按鈕代碼:

// Settings button 
    let btn = UIButton(type: .custom) 
    btn.setImage(UIImage(named: "icon-settings"), for: .normal) 
    btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) 
    btn.addTarget(self, action: #selector(showSettings(sender:)), for: .touchUpInside) 
    let settingsBtn = UIBarButtonItem(customView: btn) 
    self.navigationItem.setRightBarButton(settingsBtn, animated: false) 

行動:

let storyboard = UIStoryboard(name: "Main", bundle: nil) 
    let vc = storyboard.instantiateViewController(withIdentifier: "SettingsVC") as! SettingsViewController 
    self.navigationController?.show(vc, sender: self) 

我試圖將此代碼添加到一個單獨的實用工具類,但因爲有你不能從它進行SEGUE如果在Utility類中聲明,則無法從操作函數訪問按鈕的父級ViewController。我也嘗試繼承UINavigationController並將其分配給Storyboard中的NavigationController,但它不起作用。

+1

你需要子類'UIViewController',並讓你的每個視圖控制器的子類* *子類 – Paulw11

回答

1

您可以通過添加BaseViewController並在其中插入代碼來完成此操作。之後,在你的navigationController的rootviewController上,你只需從這個BaseViewController擴展。這樣做,並且在該函數中調用super它將始終使該代碼可用,並且不需要在每個視圖控制器中重複該代碼。

import UIKit 

class BaseViewController: UIViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Settings button 
     let btn = UIButton(type: .custom) 
     btn.setImage(UIImage(named: "icon-settings"), for: .normal) 
     btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) 
     btn.addTarget(self, action: #selector(showSettings(sender:)), for: .touchUpInside) 
     let settingsBtn = UIBarButtonItem(customView: btn) 
     self.navigationItem.setRightBarButton(settingsBtn, animated: false) 
    } 

    override func viewWillAppear(_ animated: Bool) { 
     super.viewWillAppear(animated) 
    } 

,然後在視圖控制器,你只是延長BaseViewController

class ViewController: BaseViewController { 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     //Button should already appear here 
    } 

注意的ViewController應該是你的根視圖控制器。

+0

這是一個好主意,我會仔細檢查它是我批准的,非常感謝你! –

相關問題