ios - 如何以编程方式插入右键图像 UINavigationbar swift 3

标签 ios xcode swift3 uinavigationbar uibarbuttonitem

我正在尝试以编程方式覆盖带有静态图像的导航项的 rightButton

像这样的按钮:

我已经尝试了很多时间来解决它,但仍然没有得到正确的答案。

有人可以帮我做吗?

最佳答案

可能的解决方案。您可以创建 UIBarButton 项目的扩展。 示例:

import UIKit

    extension UIBarButtonItem {

        convenience init (image: UIImage?, target: Any?, action: Selector?) {
            let button = UIButton(type: .custom)
            button.imageView?.contentMode = .scaleAspectFit
            button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
            button.addTarget(target, action: action!, for: .touchUpInside)
            button.setImage(image, for: UIControlState.normal)
            button.imageEdgeInsets = UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0)

            if #available(iOS 9.0, *) {
                button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
                button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
            }
            self.init(customView: button)
        }
    }

然后在您的 viewDidLoad 方法中使用它:

let rightButton = UIBarButtonItem(image: UIImage(named: "example"), target: self, action: #selector(exampleAction(sender:)))
self.navigationItem.rightBarButtonItem = rightButton

关于ios - 如何以编程方式插入右键图像 UINavigationbar swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48316280/

相关文章:

ios - 声明方法不可用,因为 swift 5 中的特定 iOS 版本

iphone - UIAlertView 的私有(private)方法崩溃

ios - Storyboard segues 和接收内存警告

ios - SwiftUI:如何在物理配置的设备上预览 View ?

iphone - removeFromSuperview 完成后,会显示一个白色屏幕

swift - 如何从单个设备获取两个唯一 ID

dictionary - 如何首先实现 Swift 3 字典(其中 :) closure

ios - 应用程序不再授权或在位置服务应用程序中列出

ios - 如何水平和垂直居中四个按钮?

ios - 如何在 swift 3 中获取当前日期?