swift - 这可以改变条形按钮的 "Y"位置吗?

标签 swift uibarbuttonitem

enter image description here
这是我的 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)

最佳答案

这件事太简单了。您可以尝试以下方法:

直接使用 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)

关于swift - 这可以改变条形按钮的 "Y"位置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018457/

相关文章:

ios - 在 Swift 中获取二维数组中每个数组的计数

ios - 如何在不快速类型转换的情况下从不同的类访问相同的属性

ios - 无法构建包含 Objective-C Tesseract 库的 Swift 应用程序

swift - 如何使用 Swift 在散点图上添加符号

swift - 将来自 Cognito 的用户信息与 AWS Amplify GraphQL 相关联

objective-c - 将 UISwitch 添加到 UINavigationItem

objective-c - 在 Interface Builder 中创建的 UIBarButtonItem 不起作用 - 困惑

ios - UIBarButtonItem:针对目标操作调用与 PerformSelector:withObject 的帧处理方式不同:

uinavigationbar - 使用 UINavigationBar 和 UIBarButtonItem 自动布局

iPhone SDK : UIBarButtonItem not refreshing after Memory warning