如何从UINavigation控制器隐藏“后退按钮”文本?我将只有“ <”,而没有“ <Back”
如何从UINavigation控制器隐藏“后退按钮”文本?我将只有“ <”,而没有“ <Back”
Answers:
在界面构建器中,您可以选择上一个控制器的导航项,并将Back Button字符串更改为希望后退按钮显示为的字符串。例如,如果您希望它为空白,则只需放置一个空格。
您还可以使用以下代码行对其进行更改:
[self.navigationItem.backBarButtonItem setTitle:@"Title here"];
或在Swift中:
self.navigationItem.backBarButtonItem?.title = ""
Back Button在IB中已经为空,则只需添加一个空格即可,Back然后显示箭头。
                    您也可以通过情节提要进行此操作。在上一个控制器的导航项目的属性检查器中,可以在“后退”按钮字段中设置“”。请参阅下面的图像。将“此处的标题”替换为“”。这样,您将获得所需的结果。您无需再理会“标题”。
您可以以编程方式使用
[self.navigationItem.backBarButtonItem setTitle:@" "]; 
其中self是指可以推动所需View控制器的控制器。

导航栏之前,之后的样本
之前

后

backBarButtonItem无法以编程方式进行设置,但可以通过情节提要进行设置。
                    您可以这样实现UINavigationControllerDelegate:
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
    let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
    viewController.navigationItem.backBarButtonItem = item
}class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
    }
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
        viewController.navigationItem.backBarButtonItem = item
    }
}backBarButtonItem是nil默认设置,它会影响下一个推送的控制器,因此您只需为所有控制器进行设置
将后退按钮的标题设置为@""或nil不起作用。您需要将整个按钮设置为空(没有标题或图像):
[self.navigationItem setBackBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil]];self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)这应该在导航堆栈中位于视图控制器顶部的视图控制器上完成(即,通过pushViewController方法从那里导航到VC )
对于具有大量视图控制器的情况,此问题的另一种解决方案是使用UIAppearance代理有效地隐藏后退按钮标题文本,如下所示:
UIBarButtonItem *navBarButtonAppearance = [UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil];
[navBarButtonAppearance setTitleTextAttributes:@{
    NSFontAttributeName:            [UIFont systemFontOfSize:0.1],
    NSForegroundColorAttributeName: [UIColor clearColor] }
                                      forState:UIControlStateNormal];此解决方案会将文本呈现为微小的清晰点,类似于将后退按钮标题手动设置为@" ",不同之处在于它会影响所有导航栏按钮。
我不建议将其作为此问题的一般解决方案,因为它会影响所有导航栏按钮。它将翻转范例,以便您选择何时显示按钮标题,而不是何时隐藏标题。
要选择显示标题的时间,请根据需要手动恢复标题文本属性,或创建一个UIBarButtonItem与之相同的专用子类(可能与另一个UIAppearance代理一起使用)。
如果您有一个需要隐藏大多数后退按钮标题的应用程序,而导航按钮中只有少数(或没有)是带有标题的系统按钮,那么这可能适合您!
(注意:即使文本颜色清晰,也需要更改字体大小,以确保长标题不会导致中心导航栏标题移到上方)
在viewDidLoad或loadView中添加以下代码
self.navigationController.navigationBar.topItem.title = @"";  我在iOS 9的iPhone和iPad上进行了测试
您可以添加这个Objective-C类别,以使导航控制器创建的所有“后退”按钮都没有文本。我刚刚将其添加到我的AppDelegate.m文件中。
@implementation UINavigationItem (Customization)
/**
 Removes text from all default back buttons so only the arrow or custom image shows up.
 */
-(UIBarButtonItem *)backBarButtonItem
{
    return [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
@endPS-(我不知道如何使此扩展程序与Swift一起使用,它存在奇怪的错误。欢迎进行编辑以添加Swift版本)
override迅速。非常有趣的问题
                    我在上面和下面尝试了一些,但是它们没有用。这对我有用:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.topItem?.title = ""
}没有副作用的唯一方法是创建一个自定义后退按钮。只要您不提供自定义操作,即使滑动手势也可以使用。
extension UIViewController {
func setupBackButton() {
    let customBackButton = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    navigationItem.backBarButtonItem = customBackButton
}}不幸的是,如果您希望所有后退按钮都没有标题,则需要在所有视图控制器中设置此自定义后退按钮:/
override func viewDidLoad() {
    super.viewDidLoad()
    setupBackButton()
}将标题设置为空白而不是空字符串非常重要。
以编程方式从后退按钮中删除文本,请在下面的代码中使用,它将在xcode7及更高版本中起作用。
self.navigationController.navigationBar.topItem.title = @“”;
要么
在情节提要中,在视图控制器上选择导航栏,然后在后退按钮文本中放置“”。
这将起作用。谢谢
self.navigationController?.navigationBar.topItem?.title = " "在Xcode 9中工作了!
                    当前答案无效。我想完全删除标题,但文本“ back”并没有消失。
返回上一个视图控制器并设置其title属性:
self.title = @" ";仅在以前的View Controller没有标题时有效
@""。
                    另一种方法-使用自定义NavigationBar类。
class NavigationBar: UINavigationBar {
    var hideBackItem = true
    private let emptyTitle = ""
    override func layoutSubviews() {
        if let `topItem` = topItem,
            topItem.backBarButtonItem?.title != emptyTitle,
            hideBackItem {
            topItem.backBarButtonItem = UIBarButtonItem(title: emptyTitle, style: .plain, target: nil, action: nil)
        }
        super.layoutSubviews()
    }
}也就是,此删除标题整个项目。只需为UINavigationController设置自定义类。
将上一个VC的标题设置为带有空格的“”字符串。和带有后退按钮的标题将被替换为单个空格字符串。
Self.title = " "在返回上再按一次,可将标题重置为viewWillAppear中的原始标题。
使用NavigationController覆盖的自定义pushViewController
class NavigationController: UINavigationController {  
  override func pushViewController(_ viewController: UIViewController, animated: Bool) {
    viewController.navigationItem.backBarButtonItem =
      UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    super.pushViewController(viewController, animated: animated)
  }
}我尝试了这篇文章中的所有内容。唯一有效的解决方案是@VoidLess
这是相同的答案,但更完整
class CustomNavigationController: UINavigationController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.delegate = self
    }
}
// MARK:UINavigationControllerDelegate
extension CustomNavigationController {
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
    }
}这是我的iOS11分辨率,我更改了applicationDidFinishLaunchingWithOptions中的UIBarButtonItem的外观:
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-100, 0), for:UIBarMetrics.default)您无法更改Y偏移,因为它也会在iOS11中更改后退栏按钮的位置,但在iOS10及以下版本中可以。
在Swift3中,
如果设置全局设置
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // ..
    let BarButtonItemAppearance = UIBarButtonItem.appearance()
    BarButtonItemAppearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
    BarButtonItemAppearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .highlighted)
    // ...
}Swift 3.1 您可以通过实现UINavigationController的委托方法来实现。
func navigationController(_ navigationController: UINavigationController, 
                          willShow viewController: UIViewController, animated: Bool) {
    /** It'll hide the Title with back button only,
     ** we'll still get the back arrow image and default functionality.
     */
    let item = UIBarButtonItem(title: " ", style: .plain, target: nil, 
                               action: nil)
    viewController.navigationItem.backBarButtonItem = item
}对于那些想要全局隐藏后退按钮标题的人。
您可以调配viewDidLoad的UIViewController这样。
+ (void)overrideBackButtonTitle {
    NSError *error;
    // I use `Aspects` for easier swizzling.
    [UIViewController aspect_hookSelector:@selector(viewDidLoad)
                              withOptions:AspectPositionBefore
                               usingBlock:^(id<AspectInfo> aspectInfo)
    {
        UIViewController *vc = (UIViewController *)aspectInfo.instance;
        // Check whether this class is my app's view controller or not.
        // We don't want to override this for Apple's view controllers,
        // or view controllers from external framework.
        NSString *className = NSStringFromClass([vc class]);
        Class class = [NSBundle.mainBundle classNamed:className];
        if (!class) {
           return;
        }
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:nil action:nil];
        vc.navigationItem.backBarButtonItem = backButton;
    } error:&error];
    if (error) {
        NSLog(@"%s error: %@", __FUNCTION__, error.localizedDescription);
    }
}用法:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[self class] overrideBackButtonTitle];
    return YES;
}如果你的目标iOS的13,以后你可以使用这个新的API,以全球隐藏后退按钮标题。
let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.clear]
UINavigationBar.appearance().standardAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().compactAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().scrollEdgeAppearance.backButtonAppearance = backButtonAppearance我为此苦苦挣扎,因为我有一个自定义的导航控制器。我可以使用自定义导航控制器类中的代码删除所有视图控制器中的后项文本。
override func viewDidLayoutSubviews() {
       self.navigationBar.backItem?.title = ""
    }
这将使用此自定义导航控制器删除所有后面的项目标题。
在iOS 11中,我们发现将UIBarButtonItem外观的文本字体/颜色设置为非常小的值或清除颜色将导致其他条项目消失(系统不再使用UIBarButton项目的类,它将转换为_UIModernBarButton)。将反向文本的偏移量设置为屏幕外也会在交互式弹出过程中导致闪烁。
因此我们陷入困境addSubView:
+ (void)load {
    if (@available(iOS 11, *)) {
        [NSClassFromString(@"_UIBackButtonContainerView")     jr_swizzleMethod:@selector(addSubview:) withMethod:@selector(MyiOS11BackButtonNoTextTrick_addSubview:) error:nil];
    }
}
- (void)MyiOS11BackButtonNoTextTrick_addSubview:(UIView *)view {
    view.alpha = 0;
    if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (id)view;
        [button setTitle:@" " forState:UIControlStateNormal];
    }
    [self MyiOS11BackButtonNoTextTrick_addSubview:view];
}-(void)setNavigationItems{
     UIBarButtonItem *leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"**Your title here**" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonClicked)];   
     self.navigationController.navigationBar.topItem.backBarButtonItem=leftBarButtonItem;
}
-(void)backButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}后面的文本来自最后一个View Controller的navigationItem.title,navigationItem.title并由自动设置self.title。钩子是解决问题的简便方法setTitle:,请确保navigationItem.title = @""
随意编写此代码即可AppDelegate.m。
    [UIViewController aspect_hookSelector:@selector(setTitle:)
                              withOptions:AspectPositionAfter
                               usingBlock:^(id<AspectInfo> aspectInfo, NSString *title) {
        UIViewController *vc = aspectInfo.instance;
        vc.navigationItem.titleView = ({
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
            titleLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
            titleLabel.text = title;
            titleLabel;
        });
        vc.navigationItem.title = @"";
    } error:NULL];
有关更多详细信息,请访问https://www.jianshu.com/p/071bc50f1475(简单中文)
XCode 11.5迅捷5
如果您不需要自定义后退按钮,那么一种非常简单的方法(虽然可能有点怪异)可以通过编程方式执行此操作,即在您要推入堆栈的视图控制器中将字体大小设置为零。从viewDidLoad
private func setupNavBar() {
    let appearance = UINavigationBarAppearance()
    appearance.configureWithDefaultBackground()
    
    let backButtonAppearance = UIBarButtonItemAppearance()
    backButtonAppearance.normal.titleTextAttributes = [.font: UIFont(name: "Arial", size: 0)!]
    appearance.backButtonAppearance = backButtonAppearance
    navigationItem.standardAppearance = appearance
    navigationItem.scrollEdgeAppearance = appearance
    navigationItem.compactAppearance = appearance
}终于找到了完美的解决方案,可以在整个应用程序中隐藏默认的后退文本。
只需添加一个透明图像,然后在AppDelegate中添加以下代码即可。
UIBarButtonItem.appearance().setBackButtonBackgroundImage(#imageLiteral(resourceName: "transparent"), for: .normal, barMetrics: .default)以下方法可在iOS 11上使用,并且可以确保不会在其他iOS版本上崩溃。这样做可能会使您的应用在App Store审查中被拒绝,因为UIModernBarButton和UIBackButtonContainerView都是私有API。放在AppDelegate中。
    if
        let UIModernBarButton = NSClassFromString("_UIModernBarButton") as? UIButton.Type,
        let UIBackButtonContainerView = NSClassFromString("_UIBackButtonContainerView") as? UIView.Type {
        let backButton = UIModernBarButton.appearance(whenContainedInInstancesOf: [UIBackButtonContainerView.self])
        backButton.setTitleColor(.clear, for: .normal)
    }Swift版本,在全球范围内均可完美运行:
 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal)
        UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted)
        return true
    }solution。作为@limfinity指出,这将普遍改变了所有的UIBarButtonItem的整个应用程序