我的應用程序中有多個導航控制器及其根視圖控制器。我希望每個導航欄都將社交媒體按鈕緊密地放置在欄的右側。出於同樣的我已經使用這個代碼顯示在1個視圖控制器的按鈕:消除重複的代碼Swift 3
let fbImage = UIImage(named: "Facebook.png")!
let twitterImage = UIImage(named: "Twitter.png")!
let youtbImage = UIImage(named:"YouTube.png")!
let fbBtn: UIButton = UIButton(type: .custom)
fbBtn.setImage(fbImage, for: UIControlState.normal)
fbBtn.addTarget(self, action: #selector(HomeViewController.fbBtnPressed), for: UIControlEvents.touchUpInside)
fbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let fbBarBtn = UIBarButtonItem(customView: fbBtn)
let twitterBtn: UIButton = UIButton(type: .custom)
twitterBtn.setImage(twitterImage, for: UIControlState.normal)
twitterBtn.addTarget(self, action: #selector(HomeViewController.twitterBtnPressed), for: UIControlEvents.touchUpInside)
twitterBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let twitterBarBtn = UIBarButtonItem(customView: twitterBtn)
let youtbBtn: UIButton = UIButton(type: .custom)
youtbBtn.setImage(youtbImage, for: UIControlState.normal)
youtbBtn.addTarget(self, action: #selector(HomeViewController.youtubeBtnPressed), for: UIControlEvents.touchUpInside)
youtbBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let youtbBarBtn = UIBarButtonItem(customView: youtbBtn)
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
現在我想對所有的導航條上的相同鍵。我可以很容易地在每個視圖控制器的viewDidLoad()
中複製這些代碼和相應的目標方法,但是太多的代碼正在重複。那麼如何避免這種情況呢?
我正在使用Swift 3.我是iOS新手。任何幫助將不勝感激!
您可以設置從您的UIViewController一個共同的「父母」,如「CommonViewController 「,將該代碼放入其中,並且每個ViewController都將繼承CommonViewController。 – Larme