Combine Framework Update UI doesn't work properly

吃可爱长大的小学妹 提交于 2021-01-28 19:48:39

问题


I want to try Combine framework, very simple usage, press a UIButton, and update UILabel.

My idea is:

  1. Add a publisher

@Published var cacheText: String?

  1. Subscribe

$cacheText.assign(to: \.text, on: cacheLabel)

  1. assign a value when button pressed.

cacheText = "testString"

Then the label's text should be updated.

The problem is when the button pressed, the @Published value is updated, but the UILabel value doesn't change. e.g the cacheLabel1 was assigned 123 initially but not 789 when button pressed.

Here's the full code:

ViewModel.swift

import Foundation
import Combine

class ViewModel {
    @Published var cacheText: String?

    func setup(_ text: String) {
        cacheText = text
    }

    init() {
        setup("123")
    }
}

ViewController.swift

  class ViewController: UIViewController {
    @IBOutlet weak var cacheLabel: UILabel!

    var viewModel = ViewModel()

    @IBAction func buttonPressed(_ sender: Any) {
        viewModel.setup("789")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.$cacheText.assign(to: \.text, on: cacheLabel)
    }
}

Not sure if I missed something, thanks for the help.


回答1:


The pipeline is dying before you have a chance to tap the button. You have to preserve it, like this:

var storage = Set<AnyCancellable>()
override func viewDidLoad() {
    super.viewDidLoad()
    viewModel.$cacheText.assign(to: \.text, on: cacheLabel).store(in: &storage)
}


来源:https://stackoverflow.com/questions/63239813/combine-framework-update-ui-doesnt-work-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!