【发布时间】:2020-04-11 01:52:18
【问题描述】:
我已经为此苦苦挣扎了好几个小时。我是 Swift 的新手,所以我想做的就是将购物车的图像和一个字符串添加到 .rightBarButtonItem 中,但我无法得到它。到目前为止,我有这个:
let cartIcon = UIBarButtonItem(image: UIImage(named: "shopping_cart_icon"), style: .plain, target: self, action: #selector(didTapCart(_:)))
let cartTotal = UIBarButtonItem(title: "\(cart_total)", style: .plain, target: self, action: #selector(didTapCart(_:)))
navigationItem.rightBarButtonItems = [cartIcon, cartTotal]
但是有了这个,我的图标和数字就相差 50 像素了!我还尝试使用以下方法创建自定义 UIView:
let view = UIView()
let button = UIButton(type: .system)
button.layer.shadowRadius = 5.0
// autolayout solution
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
button.semanticContentAttribute = .forceRightToLeft
button.setImage(UIImage(named: "shopping_cart"), for: .normal)
button.setTitle("\(cartItemArray.count)", for: .normal)
//button.addTarget(self, action: #selector(openDocuments), for: .touchUpInside)
button.sizeToFit()
view.addSubview(button)
view.frame = button.bounds
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: view)
但是图标很大,当我缩小它时,购物车总数又真的很远。在这两种情况下,原始图像资产都是绿色的,但它在构建时呈现系统蓝色调。我该如何解决这个问题?
【问题讨论】:
标签: swift uibarbuttonitem