Swift Custom NavBar后退按钮图像和文本

时间:2016-05-31 18:15:46

标签: ios swift uinavigationcontroller uikit uibarbuttonitem

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

这就是我所拥有的: Default Back Button

这就是我想要的: Custom Back Button

我已经尝试创建自己的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)

12 个答案:

答案 0 :(得分:56)

你可以这样做:

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

您的图片只有一种颜色

答案 1 :(得分:27)

  

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

代码段:

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)

答案 2 :(得分:18)

swift 4

在我的情况下,我只需要按钮的图像,没有任何文字。我希望这对某人有用。

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)

对于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)
}

答案 3 :(得分:9)

在带有图像和文本的导航栏中有一个按钮非常难。特别是在他们在iOS 11中引入了UIBarButtonItem位置的新头痛之后:iOS 11 - UIBarButtonItem horizontal position

您可以创建带图像的按钮或带文本的按钮,但不能创建具有这两个按钮的按钮。我甚至尝试了两个UIBarButtonItems,一个带有图像,另一个带有文本 - 它仍然看起来不太好,并且它们的UIStackView无法轻易访问以进行修改。

出乎意料的是,我找到了一个简单的解决方案:

1)在Interface Builder中将按钮设计为视图。在我的例子中,它是在目标UIViewController内部,并且为了简单起见可通过IBOutlet访问

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

enter image description here

3)使用它:

[]

就是这样。不需要使用iOS 10的负间隔技巧或iOS 11的imageInsets技巧(仅当你有图像并且不适用于图像+文本时才有效,BTW)。

enter image description here

答案 4 :(得分:8)


要设置自定义后退按钮并从后退按钮中删除文本, 仅限FROM STORYBOARD,无需任何编码。??


For setting custom back button and remove text from back button

结果:

enter image description here

答案 5 :(得分:6)

对于后退按钮图像:

  • 通过这个tutorial :(但没有为我工作)

    UINavigationBar.appearance().backIndicatorImage = UIImage(named: "imageName")
    
  • 但这stack answer :(为我工作)

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

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

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

答案 6 :(得分:2)

swift 3

    extension UIViewController {

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

    }

答案 7 :(得分:1)

只需用自定义的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)
}

答案 8 :(得分:1)

迅捷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
}

使用此处应使用

  

viewDidLoad()

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

答案 9 :(得分:0)

我已经尝试了以上所有方法,并且都制作了自定义图片而不更改文字 唯一为我工作的是来自这个answer

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

答案 10 :(得分:0)

以防万一有人需要使用 Swift5 更改所有Back按钮颜色字体UIBarButtonItem.appearance().tintColor = .red

将此添加到 AppDelegate.swift 文件。

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    // Override point for customization after application launch.        
    UIBarButtonItem.appearance().tintColor = .white
    UIBarButtonItem.appearance().setTitleTextAttributes([
        NSAttributedString.Key.foregroundColor: .red,
        NSAttributedString.Key.font: UIFont(name: "font_name", size: 14)!
    ], for: .normal)

    return true
}

}

答案 11 :(得分:0)

我知道有人回答了。在这里您可以设置标题、图片和目标。

    let view = UIView()
    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "backArrow_theme"), for: .normal)
    button.setTitle("Back to workflow", for: .normal)
    button.addTarget(self, action: #selector(onBackButton(_:)), for: .touchUpInside)
    button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
    button.sizeToFit()
    view.addSubview(button)
    view.frame = button.bounds
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: view)