这是我的UIBarButtonItem
代码,我添加了imageInsets来向其中添加“ Y”位置,但是它不起作用。
let leftBarButtonItem = UIBarButtonItem()
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
leftBarButtonItem.tintColor = .red
navigationItem.setRightBarButton(leftBarButtonItem, animated: true)
答案 0 :(得分:1)
这太简单了。您可以尝试以下方式:
直接使用UIBarButtonItem
:
let leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_2"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(rightBtnClicked(_:)))
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0)
leftBarButtonItem.tintColor = .red
self.navigationItem.setRightBarButton(leftBarButtonItem, animated: true)
或通过自定义按钮:
let rightButton = UIButton(type: UIButton.ButtonType.system)
rightButton.backgroundColor = .clear
rightButton.tintColor = .red
rightButton.frame = CGRect(origin: CGPoint(x: 10, y: 10), size: CGSize(width: 40, height: 40))
//rightButton.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 40, height: 40))
//rightButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 15, bottom: 0, right: 0)
//rightButton.contentVerticalAlignment = .bottom
rightButton.setImage(UIImage(named: "icon_1"), for: UIControl.State.normal)
rightButton.addTarget(self, action: #selector(rightBtnClicked(_:)), for: UIControl.Event.touchUpInside)
let btnView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 50, height: 50)))
btnView.backgroundColor = .clear
btnView.addSubview(rightButton)
let barBtn = UIBarButtonItem(customView: btnView)
self.navigationItem.setRightBarButton(barBtn, animated: true)