隐藏按钮文本

如何从 UINavigationController 隐藏后退按钮文本? 我将只有“ <”而不是“返回”

124963 次浏览

在 Interface Builder 中,您可以选择前一个控制器的导航项,并将 Back Button字符串更改为您希望后退按钮显示为的内容。例如,如果您希望它为空,只需要放置一个空格。

你的 can also change it代码如下:

[self.navigationItem.backBarButtonItem setTitle:@"Title here"];

或者在 斯威夫特:

self.navigationItem.backBarButtonItem?.title = ""

当前的答案是不工作。我想完全 去掉头衔,但文本“回”不走。

返回到上一个视图控制器并设置其 title 属性:

self.title = @" ";

只有当前视图控制器没有标题时,才能使用 ONLY

You could also do this through storyboard. In the attribute inspector of the navigation item of the previous controller you could set " " in the Back button field. Refer Image below. Replace "Your Title here" to " ". By doing this you will achieve the desired result. You don't need to mess with the 'Title' anymore.

可以通过编程使用

[self.navigationItem.backBarButtonItem setTitle:@" "];

其中 自我指的是推动所需视图控制器的控制器。

Xcode view controller navigation item

导航栏之前、之后的示例

之前 Before

之后 After

对于有大量视图控制器的情况,这个问题的另一个解决方案是使用 UIAppearance代理来有效地隐藏后退按钮标题文本,如下所示:

UIBarButtonItem *navBarButtonAppearance = [UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil];


[navBarButtonAppearance setTitleTextAttributes:@{
NSFontAttributeName:            [UIFont systemFontOfSize:0.1],
NSForegroundColorAttributeName: [UIColor clearColor] }
forState:UIControlStateNormal];

这个解决方案将文本呈现为一个小的透明点,类似于手动设置后退按钮标题为 @" ",除了它会影响所有的导航栏按钮。

我不建议这作为一个通用的解决方案的问题,因为它影响所有的导航栏按钮。它颠覆了模式,使您选择按钮标题 何时出现,而不是 什么时候该躲起来的标题。

To choose when to show the titles, either manually restore the title text attributes as needed, or create a specialized subclass of UIBarButtonItem that does the same (potentially with another UIAppearance proxy).

如果你有一个应用程序,其中大部分的后退按钮标题需要隐藏,只有少数(或没有)的导航按钮是系统按钮的标题,这可能是你!

(注意: 字体大小需要改变,即使文本颜色是清晰的,以确保长标题不会导致中心导航栏标题移位)

您可以像下面这样实现 UINavigationControllerDelegate:

老斯威夫特

func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}

Swift 4.x

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 is nil by default and it affects next pushed controller, so you just set it for all controllers

You can add this Objective-C category to make all "Back" buttons created by a navigation controller have no text. I just added it to my AppDelegate.m file.

@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];
}


@end

PS-(我不知道如何使这个扩展工作与斯威夫特,它有奇怪的错误。编辑欢迎添加 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
}

Add the following code in viewDidLoad or loadView

self.navigationController.navigationBar.topItem.title = @"";

我用 iOS9在 iPhone 和 iPad 上进行了测试

将后退按钮的标题设置为 @""nil将不起作用。您需要将整个按钮设置为空(没有标题或图像) :

目标 C

[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 的位置)

这是我的 xamarin.forms 代码,该类派生自 NavigationRenderer

NavigationBar.Items.FirstOrDefault().BackBarButtonItem = new UIBarButtonItem( "", UIBarButtonItemStyle.Plain, null);

to remove the Text from backbutton programmatically, used below Code this will work form xcode7 and above.

Self.navigationController.navigationBar.topItem.title =@””;

或者

在情节串连图板中,选择视图控制器上的导航栏,并在后面的按钮文本中添加“”。

这样就行了,谢谢

将上一个 VC 的标题设置为带空格的“”字符串。和标题与后退按钮将被替换为单一空格字符串。

Self.title = " "

在背面的新闻再次重置标题为原来的一个在视图 Will 出现。

唯一没有副作用的就是创建一个自定义的返回按钮。只要你不提供一个自定义的动作,甚至幻灯片的姿态工作。

extension UIViewController {
func setupBackButton() {
let customBackButton = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = customBackButton
}}

不幸的是,如果您希望不包含任何标题的所有后退按钮,则需要在所有视图控制器中设置这个自定义后退按钮:/

override func viewDidLoad() {
super.viewDidLoad()


setupBackButton()
}

设置空格作为标题而不是空字符串非常重要。

在 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)




// ...


}

我在这篇文章中尝试了所有的方法,唯一有效的解决方案是@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)
}
}

在 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];
}

This is my resolution for iOS11, I change the appearance of UIBarButtonItem in applicationDidFinishLaunchingWithOptions :

UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-100, 0), for:UIBarMetrics.default)

你不能改变 Y 偏移量,因为在 iOS11中它也会改变后栏按钮的位置,但是在 iOS10及以下版本中它是可以的。

使用覆盖 pushViewController的自定义 NavigationController

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

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
}

替代方法-使用自定义 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()
}


}

也就是说,这个删除回标题整个项目。 Just set custom class for UINavigationController.

Finally found perfect solution to hide default back text in whole app.

只需添加一个透明的图像,并添加以下代码在您的应用委托。

UIBarButtonItem.appearance().setBackButtonBackgroundImage(#imageLiteral(resourceName: "transparent"), for: .normal, barMetrics: .default)

对于那些谁想隐藏回按钮标题全球。

You can swizzle viewDidLoad of UIViewController like this.

+ (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;
}

以下方法适用于 iOS11,在其他版本的 iOS11上不会崩溃。 这样做可能会导致你的应用在 App Store 审查中被拒绝,因为 UIModern BarButton 和 UIBackButtonContainerView 都是私有 API。 置于应用代表。

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

I was struggling with this because I had a custom navigation controller. 我能够在自定义导航控制器类中使用此代码删除所有视图控制器中的后台项文本 覆盖 func viewDidLayoutSubviews (){ 项目? . title = “” }

This removes all of the back item titles using this custom navigation controller.

-(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];
}

已经有很多答案了,这是我对这个问题的看法。 I found this approach really robust. 您只需要在继续之前将其放入 viewController。

迅捷4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}

我尝试了上面和下面的一些方法,但是没有效果。这个方法对我很有效:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.topItem?.title = ""
}

背面的文字来自上一个视图控制器的 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: 10.2.1 斯威夫特: 5

  • Parent viewcontroller:
    • 自我标题 = “”
  • 儿童视图控制器:
    • Title = “ Your title”//设置 viewcontroller 的 title

如果你的目标是 IOS13,以后你可以使用 新的空气污染指数全局隐藏后退按钮标题

let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.clear]


UINavigationBar.appearance().standardAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().compactAppearance.backButtonAppearance = backButtonAppearance
UINavigationBar.appearance().scrollEdgeAppearance.backButtonAppearance = backButtonAppearance

XCode 11.5 Swift 5

这是一种非常简单的——尽管可能有点古怪的做法 如果你不需要自定义的返回按钮,那么可以在视图控制器中将字体大小设置为0,这样就可以从 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
}

UINavigationControllerDelegate's navigationController(_, willShow:, animated:) method implementation did the trick for me.

下面是全视图控制器的源代码。如果你想在整个应用程序中应用这一点,那么让所有的视图控制器都从 BaseViewController派生出来。

class BaseViewController: UIViewController {
// Controller Actions
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}


override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateNavigationBar()
}
    

//This is for custom back button image.
func updateNavigationBar() {
let imgBack = UIImage(named: "icon_back")
self.navigationController?.navigationBar.backIndicatorImage = imgBack
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = imgBack
self.navigationItem.backBarButtonItem = UIBarButtonItem()
}
}


extension BaseViewController: UINavigationControllerDelegate {
//This is to remove the "Back" text from back button.
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
viewController.navigationItem.backBarButtonItem = UIBarButtonItem()
}
}

Swift 5

viewController.navigationItem.backButtonDisplayMode = .minimal

这里大多数解决方案的问题在于,在后面的项目上设置一个空文本与长按后面按钮的新功能不能很好地工作。它没有显示正确的标题,只是显示一个空列表

Empty list on long pressing a back button

相反,您可以使用 new button display mode for iOS14或依赖于 IOS13的新外观 API来设置 文本大小为0。请注意,有些人正在玩的颜色(清晰) ,这也不工作,因为它使用的空间,并从您的标题删除它。如果标题足够长,你会看到它被剪掉了

结果代码:

public extension UINavigationBar {
func fixAppearance() {
if #available(iOS 14.0, *) {
topItem?.backButtonDisplayMode = .minimal
} else if #available(iOS 13.0, *) {
let newAppearance = standardAppearance.copy()
newAppearance.backButtonAppearance.normal.titleTextAttributes = [
.foregroundColor: UIColor.clear,
.font: UIFont.systemFont(ofSize: 0)
]
standardAppearance = newAppearance
} else {
topItem?.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
}

然后,当视图控制器出现时,您只需要调用该方法,所以您可以从基类(例如,在 viewWillAppear上)调用它,或者像本文的其他答案一样,向导航控制器添加一些委托。

在 iOS15中,我只能使用工具条外观 API 使返回按钮文本消失。看起来有点过了,但我最终还是在一个应用程序上重复使用了这个。这里有一个扩展,它包含了一些其他有用的部分,可以用来定制导航条。将 backButtonTextColor设置为 .clear可以解决这个问题。

extension UIViewController {
@objc func setNavBarAppearance(with backgroundColor: UIColor,
titleColor: UIColor? = nil,
shadowColor: UIColor? = nil,
tintColor: UIColor? = nil,
backButtonTextColor: UIColor? = nil) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = backgroundColor
    

if let titleColor = titleColor {
appearance.titleTextAttributes = [.foregroundColor: titleColor]
}


if let shadowColor = shadowColor {
appearance.shadowColor = shadowColor
}


if let tintColor = tintColor {
navigationController?.navigationBar.tintColor = tintColor
}
    

if let backButtonTextColor = backButtonTextColor {
let backButtonAppearance = UIBarButtonItemAppearance()
backButtonAppearance.normal.titleTextAttributes = [.foregroundColor: backButtonTextColor]
appearance.backButtonAppearance = backButtonAppearance
}


navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
}
}

Call it in your view controller's viewDidLoad like:

setNavBarAppearance(with: .systemBackground, backButtonTextColor: .clear)
if #available(iOS 13.0, *) {
let appearance = UINavigationBarAppearance()
appearance.backButtonAppearance.normal.titlePositionAdjustment = UIOffset.init(horizontal: -300.0, vertical: 0.0)
}else{
let barButtonApperance = UIBarButtonItem.appearance()
barButtonApperance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor:AppColor.PrimaryGray.value], for: UIControl.State.normal)


}