本文介绍了合并框架更新用户界面无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试使用 Combine 框架,非常简单的用法,按 UIButton ,并更新 UILabel .

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

我的想法是:

  1. 添加发布者

@Published var cacheText:字符串?

  1. 订阅

$ cacheText.assign(发送至:\ .text,位于:cacheLabel)

  1. 按下按钮时分配一个值.

cacheText =" testString"

然后应该更新标签的文本.

Then the label's text should be updated.

问题是当按下按钮时,更新了 @Published 值,但是 UILabel 值不变.例如,最初为 cacheLabel1 分配了 123 ,但在按下按钮时未分配 789 .

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.

这是完整的代码:

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.

推荐答案

在您有机会点击按钮之前,管道即将消失.您必须像这样保存它:

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)
}

这篇关于合并框架更新用户界面无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:21