如何使用rxswift将图像绑定到UIImageView?

时间:2019-01-26 16:15:08

标签: ios swift mvvm uiimageview rx-swift

我有viewModel:

class EditFoodViewViewModel {
    private var food: Food

    var foodImage = Variable<NSData>(NSData())

    init(food: Food) {
        self.food = food
        self.foodImage.value = food.image!
    }
}

和ViewController:

class EditFoodViewController: UIViewController {
    public var food: EditFoodViewViewModelType?
    @IBOutlet weak var foodThumbnailImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let foodViewModel = food else { return }
        foodViewModel.foodImage.asObservable().bind(to: foodThumbnailImageView.rx.image).disposed(by: disposeBag)
  }
}

在viewController的最后一行(我的UIImageView所在的行)中出现一个获取错误:

  

无法推断出通用参数'Self'

如何解决我的问题?如何使用rxSwift将图像设置为imageView?

1 个答案:

答案 0 :(得分:1)

几乎总是看到错误:“无法推断出通用参数'Self'”,这意味着类型是错误的。在这种情况下,您尝试将Observable<NSData>绑定到Observable<Image?>

您的代码还存在其他一些问题。

  • 非常罕见的是,应该使用var关键字定义Subject类型,这不是那些罕见的情况之一。您的foodImage应该是let,而不是var

  • Variable已弃用;不要使用它。在这种情况下,您甚至根本不需要主题。

  • NSData在现代Swift中也不适当。请改用Data

根据您在此处显示的内容,我希望您的代码看起来像这样:

class EditFoodViewViewModel: EditFoodViewViewModelType {
    let foodImage: Observable<UIImage?>

    init(food: Food) {
        self.foodImage = Observable.just(UIImage(data: food.image))
    }
}

class EditFoodViewController: UIViewController {

    @IBOutlet weak var foodThumbnailImageView: UIImageView!
    public var food: EditFoodViewViewModelType?
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let foodViewModel = food else { return }
        foodViewModel.foodImage
            .bind(to: foodThumbnailImageView.rx.image)
            .disposed(by: disposeBag)
    }
}