ios - 消除重复代码 Swift 3

标签 ios swift uinavigationcontroller uinavigationbar

我的应用程序中有多个导航 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/

相关文章:

ios - 为什么我不应该修改 UINavigationController 的工具栏?

ios - 导航 Controller 循环

ios - 更改图像颜色时更改 CGContext 的线宽?

c# - 我可以使用 NSStream、NSInputStream 和 NSOutputStream 从 C# 应用程序发送和接收数据吗?

ios - 将 UIView.isAccessibleElement 设置为 true 会禁用在画外音模式下单击 subview

ios - 导航栏标题对齐

ios - 为了 "reload"应用程序,注销功能应该是什么样的?

ios - 这是为性能设置属性的首选方式

ios - 及时更新标签一次显示

ios - 在自定义 UINavigationBar 中绘图,附加到顶部