ios - 如何在非根 Viewcontroller 的 ViewController 上创建具有左右按钮的导航栏?

标签 ios swift xcode uinavigationbar

enter image description here

这就是我想要的样子。我尝试使用此代码:

let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "yourImageName.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(ViewController.callMethod), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) 
//CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton

但是,当我创建导航 Controller 时,我将 map View (主屏幕)设置为导航 Controller 的 Root View Controller 。因此,该 View 不会有默认的后退按钮,因为它之前的堆栈上没有 View 。有没有办法覆盖这个,以便我的图像显示在左侧按钮上?上面的代码没有成功生成左按钮的图像。这是空白的。

最佳答案

找出答案:

    var image = UIImage(named: "ic-menu-48px.png")
    let navCon = self.navigationController
    image = self.resizeImage(image: image!, targetSize: CGSize(width: 25.0,height: 25.0))
    image = image?.withRenderingMode(.alwaysOriginal)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: nil)


  func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

关于ios - 如何在非根 Viewcontroller 的 ViewController 上创建具有左右按钮的导航栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49744415/

相关文章:

ios - 使用下一个和上一个按钮在 VC 中显示有序句子

ios - 在ios7中用日期对NSMutableArray进行排序

ios - 没有插值的 CABasicAnimation

swift - 如何使用 Vapor 3/Swift 4.1.2 创建 Heroku Worker 进程

ios - 共享扩展模式演示样式 iOS 13 无法正常工作

objective-c - Storyboard导航

ios - IAP 可用性延迟

ios - 将文本文件加载到数组结构中

ios - 在 SwiftUI 中创建新父级时 subview 不会重置

swift - SwiftLint 自定义规则的正则表达式不匹配