我正在尝试将数据从第一个VC传递到我尝试使用委托的第二个VC,但它从未起作用(未显示所需的响应),所以我也尝试了回调,现在它也起作用了,所以我粘贴了两行代码,所以欢迎任何帮助
委托:
protocol RatingDelegate: class {
func didLoadRating(ratings : [RatingModel])
}
要从中传递数据的viewcontroller
ViewController A:
var delegate : RatingDelegate?
func showRatings(ratings: [RatingModel]) {
if delegate != nil {
delegate?.didLoadRating(ratings: ratings)
}
}
应该在其中打印委托人值的地方
RatingVC:
extension RatingVC: RatingDelegate {
func didLoadRating(ratings: [RatingModel]) {
log(ratings)
}
}
回调版本
将获取数据的视图控制器
var ratingsCallBack: (() -> ([RatingModel]))?
要从中传递值的视图控制器
func showRatings(ratings: [RatingModel]) {
let ratingVC = RatingVC()
ratingVC.ratingsCallBack!() = {[unowned self] in
return ratings
}
}
这是怎么回事
表达式不可分配:函数调用返回不可变的值
答案 0 :(得分:1)
因此FirstVC将数据传递给RatingVC。
在FirstVC上,当您调用RatingVC时,应该分配委托。
let ratingVC = RatingVC()
self.delegate = ratingVC //Here you specify RatingVC is the delegate variable
self.present(ratingVC, animated: true)
也
if delegate != nil {
}
是不必要的,只需执行delegate?.didLoadRating(ratings: ratings)
使其保持清洁
编辑:对于回调版本相同,只需在初始化发送数据的视图控制器之前将值分配给回调即可。
答案 1 :(得分:0)
看起来很奇怪:
var ratingsCallBack: (() -> ([RatingModel]))?
应该是这样的:
var ratingsCallBack: (([RatingModel]) -> ())?
以防回调:
class A: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let ratingVC = RatingVC()
ratingVC.ratingsCallBack = { arr in
arr.forEach({ (model) in
print(model.rating)
})
}
navigationController?.pushViewController(ratingVC, animated: false)
}
}
class RatingVC: UIViewController {
var ratingsCallBack: (([RatingModel]) -> ())?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
@IBAction private func someButtonAction(_ sender: Any) {
let arr = [RatingModel.init(rating: 5), RatingModel()]
ratingsCallBack?(arr)
}
}
struct RatingModel {
var rating: Int = 1
}
然后,当您按“ someButton”时,将在控制器“ A”中获得此数组。