重用导航栏按钮

Reuse navigation bar button

在我的项目中,我有 UINavigationController 和三个嵌入式 UIViewController。在第一个上,我将 balanceLabelrefreshButton 添加到导航栏。当单击按钮时,首先查看控制器发送 url 请求并在标签上显示 return 值。

@IBAction func refreshButtonAction(_ sender: UIBarButtonItem) {

let operation = GetInfoOperation(...)

operation.completionBlock = { [weak self] in

  DispatchQueue.main.async {

    guard let balance = operation.output?.value?.balance else { return }
    self?.balanceLabel.text = balance
    let significantDigits = Int(Double(balance.toInt64!) * pow(10, -10))

  }
}
queue.addOperation(operation)

}

如何在其他 ViewController 上获得相同的行为,而不在每个 ViewController 中重复 @IBAction func refreshButtonAction(_ sender: UIBarButtonItem)

您可以使用继承通过扩展来存档此文件,

使用所需的所有常用功能创建所需的视图控制器,而不是直接从 UIViewController 继承,而是从该基础继承 viewController

你的基础控制器BaseViewController

class BaseViewController: UIViewController {
   //all comman functionallity 
   //add your button here 
}

class ChildOneViewController: BaseViewController {
   //this class will get all the functionality from BaseViewController
   //you can access the BaseViewController button here
   //add function for ChildOneViewController
}

 class ChildtwoViewController: BaseViewController {
   //this class will get all the functionality from BaseViewController
   //you can access the BaseViewController button here
   //add function for ChildtwoViewController
}