刚接触 stackoverflow,所以请告诉我是否需要提供额外的上下文,但我有一个 xcode 项目(健身应用程序),其中有一个选项卡栏控制器、两个名为 ProfileViewController 和 CalorieViewController 的视图控制器,它们没有 Segue 关系,但是是同一选项卡栏的一部分。我想将总卡路里从 calorieVC 传递到 profileVC 进行一些计算(totalCalories/dailyValue),并且我选择使用委托模式,我根据一些视频和教科书遵循该模式,但在我的控制台中,我说我的委托为零。
到目前为止我已经定义了委托协议:
protocol CalorieViewDelegate: AnyObject {
func didUpdateTotalCalories(_ getTotalCalories: Double)
}
第 2 步:创建委托属性:
var delegate: CalorieViewDelegate?
var totalCalories: Double = 0.0 {
didSet {
delegate?.didUpdateTotalCalories(getTotalCalories: totalCalories)
}
}
第三步:实现委托方法():
func updateTotalCalories() {
let totalCalories = breakfastFoods.reduce(0, { $0 + $1.calories }) +
lunchFoods.reduce(0, { $0 + $1.calories }) +
dinnerFoods.reduce(0, { $0 + $1.calories }) +
snackFoods.reduce(0, { $0 + $1.calories })
delegate?.didUpdateTotalCalories(getTotalCalories : totalCalories)
totalCaloriesLabel.text = "\(totalCalories)"
print(totalCalories)
if let delegate = delegate {
delegate.didUpdateTotalCalories(getTotalCalories: totalCalories)
print("Delegate called with totalCalories: \(totalCalories)")
} else {
print("Delegate is nil, cannot call didUpdateTotalCalories")
}
}
第4步:设置委托(ProfileViewController):
var calories: Double = 0.0
var dailyValue: Double = 2000.0
extension ProfileViewController: CalorieViewDelegate {
func didUpdateTotalCalories(getTotalCalories: Double) {
calories = getTotalCalories
print(calories)
}
}
这里是来自 ProfileVC 的一些更相关的代码:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let calorieVC = CalorieViewController()
calorieVC.delegate = self
}
我的项目已构建,但我需要传递该数据以完成 profileVC 中的最后计算,但我找不到它不这样做的原因。
您还可以通过使用通知观察者而不是委托方法来解决问题,例如,当您更新总卡路里时,您可以使用代码在那里发布通知观察者。您还可以使用 Userinfo 传递数据,例如:
let caloriesData:[String: String] = ["calories": "your Value"]
NotificationCenter.default.post(name: "Updatecalories", object:
nil,userInfo: caloriesData)
如果您想像其他类一样操作,可以在 ViewDidLoad() 方法中添加以下代码:
NotificationCenter.default.addObserver(
self,
selector: #selector(updateCaloriesValues(_:)),
name: "Updatecalories",
object: nil
)
并在同一个类中添加以下 Objective 方法
@objc func updateCaloriesValues(_ notification: Notification){
if let caloriesValue = notification.userInfo?["calories"] as? String
{
//Do your functionality here
}
}
您可以根据您的需要修改代码。