Reputation: 5038
Updated
I want to change offset between Arrow and Text in Back Button in Navigation Bar. It works just fine until I set
UINavigationBar.appearance().standardAppearance = newAppearance
Here is the full code:
let appearance = UINavigationBar.appearance()
let standardAppearance = UINavigationBarAppearance()
standardAppearance.configureWithOpaqueBackground()
standardAppearance.backgroundColor = someColor
standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
standardAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
standardAppearance.shadowColor = navigationShadowColor
// if remove theses 2 line, offset code works!!!
appearance.standardAppearance = standardAppearance
appearance.scrollEdgeAppearance = standardAppearance
// code to set offset
UIBarButtonItem
.appearance()
.setBackButtonTitlePositionAdjustment(
UIOffset(horizontal: -20, vertical: 0),
for: .default)
Upvotes: 3
Views: 1317
Reputation: 257533
UINavigationBar.appearance()
when specified overrides everything and has own settings for everything, so you need to configure offset via its own properties, like
...
standardAppearance.backButtonAppearance.normal.titlePositionAdjustment =
UIOffset(horizontal: -20, vertical: 0)
appearance.standardAppearance = standardAppearance
...
so the part of UIBarButtonItem.appearance()
not needed - just remove it
Upvotes: 7
Reputation: 1471
You need to set TitlePositionAdjustment in app delegate method "didFinishLaunchingWithOptions" then it will be work.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIBarButtonItem
.appearance()
.setBackButtonTitlePositionAdjustment(
UIOffset(horizontal: -20, vertical: 0),
for: .default)
return true
}
Upvotes: 1
Reputation: 2351
This is my code for a custom back button
func addBackButton() {
let backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 44))
let imageView = UIImageView(image: UIImage(named: "back-arrow"))
imageView.frame = CGRect(x: -5, y: 11, width: 12, height: 22)
imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = .fiGreen()
let label = UILabel(frame: CGRect(x: 10, y: 0, width: 60, height: 44))
label.textColor = .fiGreen()
label.text = NSLocalizedString("back", comment: "Back")
backButtonView.addSubview(imageView)
backButtonView.addSubview(label)
backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
let barButton = UIBarButtonItem(customView: backButtonView)
navigationItem.leftBarButtonItem = barButton
}
I think you can modify it to have the offset that you need.
Upvotes: 0