我必须点击按钮来更改图像。我想过使用组合,但它对我不起作用。
这是我编写的代码,我希望在加载屏幕时“radio_on”图像出现在开头,并且在我盖上按钮后我希望它显示“radio_off”图像。
import UIKit
import Combine
class ViewController: UIViewController {
@Published var isTapRow: Bool = false
private var tapRowSubscriber: AnyCancellable?
@IBOutlet weak var imageCell: UIImageView!
@IBOutlet weak var imageCellButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapRowSubscriber = $isTapRow
.receive(on: DispatchQueue.main)
.assign(to: \.isUserInteractionEnabled, on: imageCell)
if isTapRow {
imageCell.image = UIImage(named: "radio_off")
} else {
imageCell.image = UIImage(named: "radio_on")
}
}
@IBAction func imageCellButtonAction(_ sender: UIButton) {
isTapRow = sender.changesSelectionAsPrimaryAction
}
}
组合对于你想要做的事情来说有点矫枉过正,但如果你确实想这样做,下面的操场演示了一种方法:
import Combine
import PlaygroundSupport
import UIKit
class ViewController: UIViewController {
var subscription: AnyCancellable?
private var imageName = CurrentValueSubject<String, Never>("lightswitch.off")
var imageCell: UIImageView?
var imageCellButton: UIButton?
override func loadView() {
self.view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
imageCell = UIImageView(frame: CGRect(x: 20, y: 20, width: 64, height: 64))
self.view!.addSubview(imageCell!)
subscription = imageName.sink { [weak self] newName in
guard let self else { return }
self.imageCell?.image = UIImage(systemName: newName)
}
let action = UIAction(title: "Push Me") {_ in
self.imageName.value = "lightswitch.on";
}
imageCellButton = UIButton(type: .roundedRect, primaryAction: action)
imageCellButton?.frame = CGRect(x: 20, y: 128, width: 100, height: 28)
self.view!.addSubview(imageCellButton!)
}
}
PlaygroundSupport.PlaygroundPage.current.liveView = ViewController();
我在
loadView
内部创建了视图,因为这是一个游乐场,而不是一个应用程序。其中的 Combine
部分是 imageName
发布者,它广播要在 UIImageView
中使用的名称。
在 loadView 内部,我使用
sink
建立了该发布者的订阅者。当新名称发送给发布商时,我会更改 UIImageView
上的图像。
对于按钮,我创建了一个操作,当按下该按钮时,它会向发布者发送一个新值。
每次单击按钮时,它都会向
imageName
中找到的管道发送一个值,然后调用更改图像的订阅者。