首页 > 解决方案 > UIBarButtonItem 不显示

问题描述

所以我试图通过像这样子类化它来创建一个UIBarButtonItem自定义UIView

import UIKit
import SnapKit

class LocationManager: UIBarButtonItem {

    let createdView = UIView()
    lazy var currentCityLabel: UILabel = {
        let currentCityLabel = UILabel()
        currentCityLabel.text = "Philadelphia, PA"
        guard let customFont = UIFont(name: "NoirPro-SemiBold", size: 20) else {
            fatalError("""
        Failed to load the "CustomFont-Light" font.
        Make sure the font file is included in the project and the font name is spelled correctly.
        """
            )
        }
        currentCityLabel.adjustsFontForContentSizeCategory = true
        return currentCityLabel
    }()

    lazy var downArrow: UIImageView = {
        let downArrow = UIImageView()
        downArrow.contentMode = .scaleAspectFit
        downArrow.image = UIImage(named: "downArrow")
        return downArrow
    }()
    override init() {
        super.init()
        setupViews()
    }

    @objc func setupViews(){
        customView = createdView

        createdView.addSubview(currentCityLabel)
        currentCityLabel.snp.makeConstraints { (make) in
            make.left.equalTo(createdView.snp.left)
            make.top.bottom.equalTo(createdView)
        }

        createdView.addSubview(downArrow)
        downArrow.snp.makeConstraints { (make) in
            make.left.equalTo(currentCityLabel.snp.right).offset(5)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

但是,当我创建它并将其分配给我时,我viewController什么也看不到

import UIKit

class ViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }

    @objc func setupViews(){
        guard let collection = collectionView else {
            return
        }
        collection.backgroundColor = .white
        let customLeftBar = LocationManager()
        self.navigationController?.navigationItem.leftBarButtonItem = customLeftBar
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我看过其他帖子,似乎没有一个完全符合我的情况。我开始认为这是因为我没有给出UIViewa 框架,但我不确定在这种情况下我将如何做到这一点。任何人都看到了我看不到的任何东西,这可能会帮助我解决这个问题。设定目标也不起作用我尝试了两种不同的方法,但都没有触发任何事情

  @objc func setupBarButtonItems(){
        let customLeftBar = LocationManager()
        customLeftBar.action = #selector(self.leftBarPressed)
        customLeftBar.target = self
        customLeftBar.customView?.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.leftBarPressed))
        customLeftBar.customView?.addGestureRecognizer(tapGesture)
        navigationItem.leftBarButtonItem = customLeftBar
    }


    @objc func leftBarPressed(){
        print("left bar tapped")
    }

标签: iosswiftuinavigationcontrolleruinavigationitem

解决方案


更改您的添加行

self.navigationController?.navigationItem.leftBarButtonItem = customLeftBar

self.navigationItem.leftBarButtonItem = customLeftBar

添加 barItem 时,您需要通过添加它,navigationItemViewController不是NavigationController

已编辑以添加操作

您的自定义UIBarButtonItemCustom View's BarButtonItem,因此targetandselector将不起作用。

您可以通过在 customView 中添加按钮来添加自定义操作,并通过闭包发送操作

初始化你的闭包

var didSelectItem: (() -> Void)?

将创建按钮代码添加到您的 @objc func setupViews()

    let button = UIButton(type: .custom)
    createdView.addSubview(button)
    button.snp.makeConstraints { (maker) in
        maker.top.bottom.leading.trailing.equalTo(createdView)
    }
    // button.backgroundColor = UIColor.cyan // uncomment this line for understand about the barbuttonitem's frame

    button.addTarget(self, action: #selector(didTap(_:)), for: .touchUpInside)

并添加功能

@objc func didTap(_ button: UIButton) {
    print("Did tap button")
}

在您的 viewController 中,您可以通过以下方式获取点击操作

customLeftBar.didSelectItem = { [weak self] in
    self?.leftBarPressed()
}

不幸的是,你的 barbuttonitem 的默认框架是 30x30,所以你必须为你的 barbuttonitem 设置框架。如果没有,您只能在 30x30 区域内捕捉点击动作(取消注释代码以查看它)


推荐阅读