我已经坚持了好几天了。我的rightBarButtonItem有问题。我想创建一个自定义视图。在自定义视图中,有2个项目:标签,imageView。当我输入以下内容时:

let customView = UIView()
    customView.translatesAutoresizingMaskIntoConstraints = false
    customView.backgroundColor = .black
    customView.frame = CGRect(x: 0, y: 0, width: 90, height: 40)

    let coinLabelNavigationBar = UILabel()
    coinLabelNavigationBar.frame = CGRect(x: 40, y: 0, width: 30, height: 25)
    coinLabelNavigationBar.translatesAutoresizingMaskIntoConstraints = false
    coinLabelNavigationBar.text = "200"
    coinLabelNavigationBar.font = UIFont(name: ".SFUIText-Medium", size: 20)
    coinLabelNavigationBar.textColor = UIColor.white

    let coinImage = UIImageView()
    coinImage.frame = CGRect(x: 75, y: 0, width: 25, height: 25)
    coinImage.translatesAutoresizingMaskIntoConstraints = false
    coinImage.image = UIImage(named: "Coin")

    customView.addSubview(coinLabelNavigationBar)
    customView.addSubview(coinImage)

    let rightBarButton = UIBarButtonItem(customView: customView)

    navigationItem.rightBarButtonItem = rightBarButton

它不起作用,navigationBar向我显示了这一点:
ios - 在导航栏中设置rightBarButtonItem-LMLPHP

您有什么想法,如何解决?

感谢您的回答。

最佳答案

尝试这个 -

let customView = UIView()
//        customView.translatesAutoresizingMaskIntoConstraints = false
    customView.backgroundColor = .black
    customView.frame = CGRect(x: 0, y: 0, width: 90, height: 40)

    let coinLabelNavigationBar = UILabel()
    coinLabelNavigationBar.frame = CGRect(x: 40, y: 0, width: 30, height: 25)
//        coinLabelNavigationBar.translatesAutoresizingMaskIntoConstraints = false
    coinLabelNavigationBar.text = "200"
    coinLabelNavigationBar.font = UIFont(name: ".SFUIText-Medium", size: 20)
    coinLabelNavigationBar.textColor = UIColor.white

    let coinImage = UIImageView()
    coinImage.frame = CGRect(x: 75, y: 0, width: 25, height: 25)
 //        coinImage.translatesAutoresizingMaskIntoConstraints = false
    coinImage.image = UIImage(named: "coin.jpg")

    customView.addSubview(coinLabelNavigationBar)
    customView.addSubview(coinImage)

    let rightBarButton = UIBarButtonItem(customView: customView)

    navigationItem.rightBarButtonItem = rightBarButton

10-08 06:09