我的应用程序中有多个导航 Controller 及其 Root View Controller 。我希望每个导航栏都将社交媒体按钮紧密放置在栏的右侧。同样,我使用此代码在 1 个 View Controller 中显示按钮:
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)
现在我想要在所有导航栏上使用相同的按钮。我可以轻松地在每个 View Controller 的 viewDidLoad()
中复制这段代码和相应的目标方法,但是重复的代码太多了。那么如何避免这种情况呢?
我正在使用 Swift 3。我是 iOS 新手。任何帮助将不胜感激!
最佳答案
大多数重复都是通过使用函数来解决的。第一步是将该代码提取到一个函数中,第二步是从多个地方使用同一个函数。
您可以将其添加到扩展中,例如:
extension UIViewController {
func addShareButtons() {
...
self.navigationItem.setRightBarButtonItems([youtbBarBtn, twitterBarBtn, fbBarBtn], animated: false)
}
}
只调用
self.addShareButtons()
来自每个需要按钮的 Controller 。
您也可以向扩展添加按钮处理程序。
另一种方法是使用 UIViewController
子类,但如果您想使用 UITableViewController
子类,这总是一个问题。
关于ios - 消除重复代码 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42200268/