【问题标题】:UITabBarController Shared Data Model - share & update model from anywhereUITabBarController 共享数据模型 - 从任何地方共享和更新模型
【发布时间】:2021-06-22 23:00:23
【问题描述】:

我正在使用 TabBarcontroller 类型的应用程序,并且我正在使用表单的共享模型:

enum WorkoutState {
  case Stopped
  case Started
  case Paused
}

class BaseTBController: UITabBarController {
  var workoutState: WorkoutState? = .Stopped
}  

目前一切正常,我可以使用

访问和更新不同选项卡中的变量
let tabbar = tabBarController as! BaseTBController
if tabbar.workoutState = .Stop {
  //do something
  tabbar.workoutState = .Start
}

现在的情况是,我似乎需要将它放在我的代码中。例如:

startRun()
resumeRun()
pauseRun()

有没有更好的方法来代替放置

let tabbar = tabBarController as! BaseTBController
tabbar.workoutState = .Start

在 3 个函数中的每一个中?

【问题讨论】:

    标签: ios swift uitabbarcontroller


    【解决方案1】:

    你总是可以使用协议和默认扩展来实现你所需要的

    protocol HandleWorkStateProtocol where Self: UIViewController {
        func updateWorkOutState(to: WorkoutState)
    }
    
    extension HandleWorkStateProtocol {
        func updateWorkOutState(to state: WorkoutState) {
            guard let tabBarController = self.tabBarController as? BaseTBController else { return }
            tabBarController.workoutState = state
        }
    }
    

    在您查看具有这 3 种方法(startRun、resumeRun、pauseRun)的所有控制器中,只需确认此协议并使用适当的值调用 updateWorkOutState(to: 来修改状态

    class SomeTestViewController: UIViewController {
        func startRun() {
            self.updateWorkOutState(to: .Started)
        }
    
        func resumeRun() {
    
        }
    
        func pauseRun() {
            self.updateWorkOutState(to: .Paused)
        }
    }
    
    extension SomeTestViewController: HandleWorkStateProtocol {}
    

    附言

    枚举的大小写值不遵循 Stopped 这样的 Pascal 大小写,而是遵循 Camel 大小写 stopped,因此将枚举值更改为

    enum WorkoutState {
      case stopped
      case started
      case paused
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 2018-04-03
      • 2020-10-18
      相关资源
      最近更新 更多