gpt4 book ai didi

ios - 如何在点击按钮时观察 PublishSubject

转载 作者:行者123 更新时间:2023-12-02 06:29:31 25 4
gpt4 key购买 nike

我正在处理这样的情况,我想在这里应用 RxSwift。

我有带有按钮的.xib UIView。

class RightButtonItemView: UIView {

@IBOutlet weak var rightButtonimageView: UIImageView!
@IBOutlet weak var rightButtonButton: UIButton!

let performEventSegue = PublishSubject<Bool>()

class func instanceFromNib() -> RightButtonItemView {
return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! RightButtonItemView
}

override func awakeFromNib() {
//I'm not sure how should I link button tap and my subject
rightButtonButton.rx.tap
}
}

我在 viewController 中创建了此 View 的实例

var rightButtonItemView = RightButtonItemView.instanceFromNib()

在我的 segue 中单击此按钮时,我需要移至下一个 VC,因此我订阅了 UIView 的主题

rightButtonItemView.performEventSegue.asObserver().subscribe(onNext: { (isAuthorized) in

if isAuthorized {
let storyboard = UIStoryboard(name: "Notifications", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "UserNotificationsViewController")
self.present(viewController, animated: true, completion: nil)
}
})

但我不知道如何将按钮点击与发布主题的状态更改相链接?

最佳答案

在这种情况下您使用bind 运算符:

class RightButtonItemView: UIView {

@IBOutlet weak var rightButtonimageView: UIImageView!
@IBOutlet weak var rightButtonButton: UIButton!

let performEventSegue = PublishSubject<Void>()
private let bag = DisposeBag()

class func instanceFromNib() -> RightButtonItemView {
return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! RightButtonItemView
}

override func awakeFromNib() {
rightButtonButton.rx.tap
.bind(to: performEventSegue)
.disposed(by: bag)
}
}

--更新--

我想到了这个解决方案,我认为它更好。您根本不需要主题:

class RightButtonItemView: UIView {

@IBOutlet weak var rightButtonButton: UIButton!

var performEventSegue: Observable<Void> {
return rightButtonButton.rx.tap.asObservable()
}
}

关于ios - 如何在点击按钮时观察 PublishSubject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com