我一直试图在导航栏中的hamburger
右侧放置一个titleView
按钮(三行平行线),但是每次这样做,我覆盖的图像都会被覆盖整个导航栏,并删除我在titleView
中拥有的图像。
如果我在情节提要编辑器中选择默认图像,它将显示在导航栏的右侧,没有任何问题,但是,一旦在情节提要编辑器中选择“汉堡包”按钮,我将遇到与以前相同的问题。我尝试使用多个不同的图像,但对代码进行了一些改动,但均未成功。有没有办法调整我正在使用的图像的大小,使其适合导航栏,还是我的代码有问题?
这是我来自下面viewController.swift
的代码:
override func viewDidAppear(_ animated: Bool) {
let nav = self.navigationController?.navigationBar
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
imageView.contentMode = .scaleAspectFit
let titleImage = UIImage(named: "logowhitecircle")
imageView.image = titleImage
navigationItem.titleView = imageView
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
menuButton.contentMode = .scaleAspectFit
let menuImage = UIImage(named: "hamburgericon")
menuButton.setImage(menuImage, for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menuButton)
答案 0 :(得分:0)
尝试使用以下代码:
let imageBurger = UIImage(named: "hamburgericon")!
let btnLeftMenu = UIButton(type: .system)
btnLeftMenu.bounds = CGRect(x: 10, y: 0, width: imageBurger.size.width, height: imageBurger.size.height)
btnLeftMenu.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
btnLeftMenu.setImage(imageBurger, for: UIControl.State())
btnLeftMenu.setTitle(title, for: .normal)
let leftButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = leftButton
答案 1 :(得分:0)
尝试使用此模块 FFBadgedBarButtonItem ,它很容易使用,这是文档Link
下面是我的代码如何实现它!
let image = UIImage(named: "yourImage")
let finalImage = resizeImage(image: image!, newWidth: 30)
navigationItem.rightBarButtonItem = FFBadgedBarButtonItem(image: finalImage, target: self, action: #selector(rightButtonTouched))
这是调用函数
@objc func rightButtonTouched() {
// what event you need to perfom by clicking on this button
}
您需要创建桥接头才能使用此Obj-C模块。
:D
答案 2 :(得分:0)
尝试一下:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//create a new button
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
//set image for button
button.setImage(UIImage(named: "hamburgericon"), forState: UIControlState.Normal)
//add function for button
button.addTarget(self, action: "customButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
//set frame
button.frame = CGRectMake(0, 0, 40, 40)
let barButton = UIBarButtonItem(customView: button)
//assign button to navigationbar
self.navigationItem.rightBarButtonItem = barButton
}
//This method will call when you press button.
func customButtonPressed() {
println("button pressed")
}
}
答案 3 :(得分:0)
您需要在图像资源中设置图像大小,例如 3x = 84px,2x = 56px,1x = 28px ,
有关更多信息,请参阅Apple文档:https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/custom-icons/
let menuButton = UIBarButtonItem(image: UIImage(named: "logowhitecircle"), style: .plain, target: self, action: #selector(menuButtonTapped(_:)))
self.navigationItem.rightBarButtonItem = menuBu
tton