swift 为什么tabBar.rx.didSelectItem没有发出tap事件?

ezykj2lf  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(167)

当我点击tabBarItem“书签”时,我期望下面的代码块将被打印:“select tabbar item”,不要打印“root view tapped“。
实际上console打印“root view tapped”。有人能告诉我为什么它没有像我预期的那样工作,以及如何修复它吗?
顺便说一下,我确实问了chatGPT,但没有得到正确的答案。
下面是完整的代码

import UIKit
import RxSwift
import RxCocoa

class TabBarViewController: UIViewController {
    private let disposeBag = DisposeBag()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // create a UITabBar 
        let tabBar = UITabBar()
        self.view.addSubview(tabBar)
        tabBar.translatesAutoresizingMaskIntoConstraints = false
        tabBar.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        tabBar.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        tabBar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        let item1 = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.bookmarks, tag: 1)
        let item2 = UITabBarItem(tabBarSystemItem: UITabBarItem.SystemItem.contacts, tag: 2)
        tabBar.items = [item1, item2]
        self.view.bringSubviewToFront(tabBar)
        
        // create a red container view
        let red = UIView()
        red.backgroundColor = UIColor.red
        self.view.addSubview(red)
        red.translatesAutoresizingMaskIntoConstraints = false
        red.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        red.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        red.bottomAnchor.constraint(equalTo: tabBar.topAnchor).isActive = true
        red.heightAnchor.constraint(equalTo: tabBar.heightAnchor).isActive = true
        
        
        
        
        tabBar.rx.didSelectItem.subscribe(onNext: { e in
            print("select tabbar item ")
        })
        .disposed(by: disposeBag)
        
        
        red.rx.tapGesture()
            .when(.recognized)
            .subscribe { ele in
                print("red tapped")
            }
            .disposed(by: disposeBag)
        
        
        view.rx.tapGesture(configuration: { tapGestureRecognizer, delegate in
            delegate.simultaneousRecognitionPolicy = .never
        })
        .when(.recognized)
        .subscribe(onNext: { ele in
            print("root view tapped ")
        })
        .disposed(by: disposeBag)
    }
    
    
}
mpgws1up

mpgws1up1#

我已经想明白了。superview中的点击识别器已成功识别,因此UIEvent不会传播到UITabBar。这就是UITabBar未打印的原因:“选择选项卡栏项目”
参考官方文件:
窗口在将触摸事件递送到附接到手势识别器的命中测试视图之前将触摸事件递送到手势识别器。通常,如果手势识别器分析多点触摸序列中的触摸流并且不识别其手势,则视图接收触摸的完整补充。如果手势识别器识别出其手势,则视图的剩余触摸被取消。手势识别中的通常操作序列遵循由cancelsTouchesInView、delaysTouchesBegan、delaysTouchesEnded属性的默认值确定的路径。

相关问题