ios Swift 自定义导航栏后退按钮图像和文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37552876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:12:38  来源:igfitidea点击:

Swift Custom NavBar Back Button Image and Text

iosswiftuinavigationcontrolleruikituibarbuttonitem

提问by Conor

I need to customise the look of a back button in a Swift project.

我需要在 Swift 项目中自定义后退按钮的外观。

Here's what I have: Default Back Button

这是我所拥有的: 默认返回按钮

Here's what I want: Custom Back Button

这是我想要的: 自定义后退按钮

I've tried creating my own UIBarButtonItem but I can't figure out how to get the image to be beside the text, rather than as a background or a replacement for the text.

我尝试创建自己的 UIBarButtonItem,但我不知道如何将图像放在文本旁边,而不是作为背景或文本的替代品。

let backButton = UIBarButtonItem(title: "Custom", style: .Plain, target: self, action: nil    )
//backButton.image = UIImage(named: "imageName") //Replaces title
backButton.setBackgroundImage(UIImage(named: "imageName"), forState: .Normal, barMetrics: .Default) // Stretches image
navigationItem.setLeftBarButtonItem(backButton, animated: false)

回答by Randy

You can do something like that:

你可以这样做:

let yourBackImage = UIImage(named: "back_button_image")
self.navigationController?.navigationBar.backIndicatorImage = yourBackImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
self.navigationController?.navigationBar.backItem?.title = "Custom"

Your image will only have one color though

虽然您的图像只有一种颜色

回答by Supratik Majumdar

Note: Please remember that the back button belongs to the the source ViewController and not to the destination ViewController. Thus, the modification needs to be done in the source VC, which is reflected to all the view in the navigation controller

注意:请记住后退按钮属于源 ViewController 而不是目标 ViewController。因此,需要在源VC中进行修改,并反映到导航控制器中的所有视图中

Code Snippet:

代码片段:

let backImage = UIImage(named: "icon-back")

self.navigationController?.navigationBar.backIndicatorImage = backImage

self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage

/*** If needed Assign Title Here ***/
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)

回答by Booharin

swift 4

迅捷 4

In my case, I needed to have only the image of the button, without any text. I hope this will be useful to someone.

就我而言,我只需要按钮的图像,没有任何文本。我希望这对某人有用。

let imgBackArrow = UIImage(named: "back_arrow_32")

navigationController?.navigationBar.backIndicatorImage = imgBackArrow
navigationController?.navigationBar.backIndicatorTransitionMaskImage = imgBackArrow

navigationItem.leftItemsSupplementBackButton = true
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)

For iOS 12 you can do

对于 iOS 12,你可以这样做

func setNavigationBar() {

    self.navigationItem.setHidesBackButton(true, animated:false)

    //your custom view for back image with custom size
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    let imageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 20, height: 20))

    if let imgBackArrow = UIImage(named: "icn_back_arrow") {
        imageView.image = imgBackArrow
    }
    view.addSubview(imageView)

    let backTap = UITapGestureRecognizer(target: self, action: #selector(backToMain))
    view?.addGestureRecognizer(backTap)

    let leftBarButtonItem = UIBarButtonItem(customView: view ?? UIView())
    self.navigationItem.leftBarButtonItem = leftBarButtonItem
}

@objc func backToMain() {
    self.navigationController?.popViewController(animated: true)
}

回答by Vitalii

Having a button in Navigation Bar with Image AND Text is quite hard. Especially after they have introduced a new headache with UIBarButtonItem position in iOS 11: iOS 11 - UIBarButtonItem horizontal position

在导航栏中有一个带有图像和文本的按钮非常困难。特别是在他们在 iOS 11 中引入了令人头疼的 UIBarButtonItem 位置之后:iOS 11 - UIBarButtonItem 水平位置

You can make either button with image or a button with text, but not a button with both of those. I even tried two UIBarButtonItems together, one with image and other with text - it still doesn't look good at all and their UIStackView can't be easily accessed for modification.

您可以制作带有图像的按钮或带有文本的按钮,但不能同时制作带有两者的按钮。我什至尝试了两个 UIBarButtonItems,一个带有图像,另一个带有文本 - 它仍然看起来不太好,并且无法轻松访问它们的 UIStackView 进行修改。

Unexpectedly I found a plain simple solution:

没想到我找到了一个简单的解决方案:

1) design the button as view in Interface Builder. In my case it is inside target UIViewController and accessible via IBOutlet for simplicity

1)在Interface Builder中将按钮设计为视图。就我而言,它位于目标 UIViewController 内,为简单起见,可通过 IBOutlet 访问

2) set Leading Space constraint for the image to be negative, you might also want to set view's background color to .clear.

2) 将图像的前导空间约束设置为负数,您可能还想将视图的背景颜色设置为 .clear。

enter image description here

在此处输入图片说明

3) use it:

3)使用它:

@IBOutlet var backButtonView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    let backButton = UIBarButtonItem(customView: self.backButtonView)
    self.backButtonView.heightAnchor.constraint(equalToConstant: 44).isActive = true // if you set more than you'll get "Unable to simultaneously..."
    self.backButtonView.widthAnchor.constraint(equalToConstant: 75).isActive = true
    self.navigationItem.leftBarButtonItem = backButton
}

That's it. No need to use the trick with negative spacer for iOS 10 or the trick with imageInsets for iOS 11 (which works only if you have image and doesn't work for image+text, BTW).

就是这样。无需对 iOS 10 使用带有负间隔的技巧或用于 iOS 11 的带有 imageInsets 的技巧(仅当您有图像时才有效,对图像+文本无效,顺便说一句)。

enter image description here

在此处输入图片说明

回答by Idan

For the back button image:

对于后退按钮图像:

  • By this tutorial: (but didn't work for me)

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "imageName")
    
  • But this stack answer: (worked for me)

    var backButtonImage = UIImage(named: "back-button-image")
    backButtonImage = backButtonImage?.stretchableImage(withLeftCapWidth: 15, topCapHeight: 30)
    UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
    
  • 通过本教程:(但对我不起作用)

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "imageName")
    
  • 但是这个堆栈答案:(对我有用)

    var backButtonImage = UIImage(named: "back-button-image")
    backButtonImage = backButtonImage?.stretchableImage(withLeftCapWidth: 15, topCapHeight: 30)
    UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
    

And for the font, assuming you want the font to match for the whole navigation bar:(currently in use)

对于字体,假设您希望字体与整个导航栏匹配:(当前正在使用)

if let font = UIFont(name: "Avenir-Book", size: 22) {
  UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font]
}

回答by Mushrankhan



For setting custom back bar button and remove text from back bar button, FROM STORYBOARD only, without any coding.

用于设置自定义后退栏按钮并从后退栏按钮中删除文本,仅来自故事板,无需任何编码。



For setting custom back button and remove text from back button

用于设置自定义后退按钮并从后退按钮中删除文本

RESULT:

结果:

enter image description here

在此处输入图片说明

回答by Mohamed Saleh

I have tried all the above and all make the custom image without changing the text The only one worked for me is from this answer

我已经尝试了以上所有方法,并且都在不更改文本的情况下制作了自定义图像唯一对我有用的是来自这个答案

let backBTN = UIBarButtonItem(image: UIImage(named: "Back"), 
                              style: .plain, 
                              target: navigationController, 
                              action: #selector(UINavigationController.popViewController(animated:)))
navigationItem.leftBarButtonItem = backBTN
navigationController?.interactivePopGestureRecognizer?.delegate = self

回答by Ahmed Safadi

swift 3

迅捷 3

    extension UIViewController {

        func setBackButton(){
            let yourBackImage = UIImage(named: "backbutton")
            navigationController?.navigationBar.backIndicatorImage = yourBackImage
            navigationController?.navigationBar.backIndicatorTransitionMaskImage = yourBackImage
        }

    }

回答by ikbal

Swift 4.2 Add this functions ViewController

Swift 4.2 添加此功能 ViewController

func addNavigationBarButton(imageName:String,direction:direction){
    var image = UIImage(named: imageName)
    image = image?.withRenderingMode(.alwaysOriginal)
    switch direction {
    case .left:
       self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    case .right:
       self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
    }
}

@objc func goBack() {
    navigationController?.popViewController(animated: true)
}

enum direction {
    case right
    case left
}

Using you should use here

使用你应该在这里使用

viewDidLoad()

viewDidLoad()

addNavigationBarButton(imageName: "ic_back", direction:.left)

回答by Mohamed Ali

Just replace the backButton with a custom rightBarButtonItem

只需用自定义 rightBarButtonItem 替换 backButton

let backImage = UIImage(named: "BackBtn")?.withRenderingMode(.alwaysOriginal)
    navigationItem.leftBarButtonItem = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(popnav))

    @objc func popnav() {
    self.navigationController?.popViewController(animated: true)
}