这就是我想要的样子。我尝试使用此代码:
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/