iOS 自定义导航栏后退按钮标题在点击时消失

标签 ios swift uinavigationcontroller uikit uibarbuttonitem

StackOverflow 社区您好,

我有一个相当奇怪的情况,导航 Controller 的导航栏上的自定义后退按钮在交互时消失。

一些附加信息是我的代码没有使用 Storyboard,而是使用 UIKit - 包括 UI 在内的所有内容都是以编程方式构建的。

这是我的设置:

  • 我首先创建一个自定义 UINavigationController 子类,以抽象出所有与导航 Controller 相关的自定义设置

  • 在这个子类中,我有一个方法可以调用来自定义后退按钮的外观

private func customizeBackButton() {
    let backImage = UIImage(named: "BackButton")?.withRenderingMode(.alwaysOriginal)
    navigationBar.backIndicatorImage = backImage
    navigationBar.backIndicatorTransitionMaskImage = backImage
    
    UIBarButtonItem.appearance().setTitleTextAttributes([
      NSAttributedString.Key.foregroundColor: UIColor.panoStoryYellow,
      NSAttributedString.Key.font: UIFont(name: "Montserrat-SemiBold", size: 15)!
    ], for: .normal)
}
  • 上述自定义给出了以下结果,这正是我想要的结果,其中图库是我上一个屏幕的标题

UINavigationController custom back button

  • 当我点击后退按钮最左边的箭头时,该按钮可以正常工作。但是,如果我点击后退按钮的标签部分(图库文本所在的位置),文本就会消失并使用户保持在同一屏幕上。

UINavigationController UINavigationBarButton back button disappears

当我在标签消失后点击后退箭头时,它会起作用并将我带回到上一个屏幕,但是,为什么会发生这种消失?

我尝试了什么 我已经尝试了许多关于堆栈溢出的建议,例如:

  • 确保我的代码中没有任何行显式隐藏后退按钮
  • 随时检查上一屏幕的标题是否为空字符串

我可以确认这些不是问题,因为我有有效的标题并且从不隐藏后退按钮。

以下是我在确定它们都不适合我的案例之前检查过的一些资源,我在这里提出了问题:

UINavigationController Back Button not visible, but works

UINavigationController's back button disappears?

Navigation title disappears after use of custom back button

navigation title on previous screen disappear when back button pressed

Missing Navigation's or Back Button's Title When Push ViewControllers in Succession

关于为什么此后退按钮文本消失有什么想法吗?

最佳答案

经过多次尝试和错误,这似乎对我有用。

我什至需要指定突出显示 状态的属性。

UIBarButtonItem.appearance().setTitleTextAttributes([
      NSAttributedString.Key.foregroundColor: UIColor.panoStoryYellow,
      NSAttributedString.Key.font: UIFont(name: "Montserrat-SemiBold", size: 15)!
], for: .highlighted)

此后,文本从未消失,一切都按预期进行。

我暂时不会将此标记为答案,因为也许有人有更好的“正确”方法来做到这一点。

无论如何,如果其他人可能面临类似的情况,我会将这个答案放在这里。

关于iOS 自定义导航栏后退按钮标题在点击时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68148746/

相关文章:

ios - CNContactViewController setEditing true before appear

ios - iOS7中拦截后退导航

没有通知中心的 iOS 虚拟键盘大小

iphone - 如何知道哪个 xib 文件使用了图像?

ios - 如何将 int 转换为 nsindexpath?

objective-c - iOS:创建 UINavigationController 的副本

ios - MKMapView 不填充 View (iOS)

ios - 带有 HTTP 身份验证的 NSURLRequest

Swift 4.2 imagePickerController 问题

ios - 关闭两个 View Controller 然后推送一个 View Controller - Swift