我的应用程序中有多个导航控制器及其根视图控制器。我希望每个导航栏都将社交媒体按钮紧密地放置在栏的右侧。出于同样的我已经使用这个代码显示在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