Search code examples
iosswiftuinavigationcontrolleruinavigationbaruinavigationitem

Added UIBarButtonItem covers UINavigationController back button


I added a UIBarButtonItem to self.navigationItem.leftBarButtonItem when my app runs on RTL device configuration and self.navigationItem.rightBarButtonItem when LTR device configuration. In both configuration added UIBarButtonItem covers the back button which is the defualt button.

Here is my code:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: CGFloat(150), height: CGFloat(20)))
    label.backgroundColor = UIColor.clear
    label.font = UIFont.systemFont(ofSize: 18.0)
    label.shadowColor = UIColor(white: 0.0, alpha:0.5)
    label.textAlignment = NSTextAlignment.center
    label.textColor = UIColor(hexaValue: ConsColors.albums)
    label.text = "Just text"
    label.sizeToFit()
    if UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.rightToLeft{
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: label)
    }else{
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: label)
    }

I even tried with a normal system UIBarButtonItem. Also tried to set UINavigationcontroller semantic Content Attribute force RightToLeft or LefttoRight which doesn't work.

UINavigationBar.appearance().semanticContentAttribute = .forceRightToleft

I use Swift 3, Xcode 8.1 and an iPad Air 2 with it's OS verion being 9.3.2 Does anyone know how to fix it?

Will appreciate the help, Thanks.


Solution

  • Set this property below

    self.navigationItem.leftItemsSupplementBackButton = true
    

    This will make sure custom buttons are added after the back button

    Update:

    As per my understanding, your requirement is to have default back button and a custom button in opposite side. The below condition is not required for that

        if UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.rightToLeft{
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: label)
        }else{
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: label)
        }
    

    Replace that with

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: label)