美文网首页
custom自定义导航栏的titleView图片和标题一起居中

custom自定义导航栏的titleView图片和标题一起居中

作者: 授之以渔不如授之以鱼 | 来源:发表于2021-09-09 09:39 被阅读0次

需求:
导航栏中间是图片和标题一起居中,点击可跳转下一页
效果:


image.png

在适配导航栏时发现点击跳转会往右偏移约20pt的问题,我尝试过用button和view作为一个titleView,并设置它的frame为

ChatAvatarTitleView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))

但仍出现抖动,所以我想到了用stackView来做,但是我很少用这个控件,一开始我还是把stackView放在一个view里面,再把这个view设置宽高并作为titleView,但是仍出现偏移的问题,所以titleView在外面不应该给frame设定值。

代码:

        let imageView = UIImageView()
        NSLayoutConstraint.activate([
            imageView.heightAnchor.constraint(equalToConstant: 24),
            imageView.widthAnchor.constraint(equalToConstant: 24)
        ])
        imageView.backgroundColor = .red
        
        let titleLabel = UILabel()
        titleLabel.text = "Custom title"
        
        let hStack = UIStackView(arrangedSubviews: [imageView, titleLabel])
        hStack.spacing = 8
        hStack.alignment = .center
        
        navigationItem.titleView = hStack
        
        let tapTitleGesture = UITapGestureRecognizer()
        hStack.addGestureRecognizer(tapTitleGesture)
        tapTitleGesture.rx.event
            .subscribe(onNext: {[unowned self] _ in
                Logger.log("点击导航栏跳转个人中心")
            }).disposed(by: vm.disposeBag)

打印点击事件

ChatViewController.swift:(#518) setBarItem():点击导航栏跳转个人中心

相关文章

网友评论

      本文标题:custom自定义导航栏的titleView图片和标题一起居中

      本文链接:https://www.haomeiwen.com/subject/kwliwltx.html