简体   繁体   中英

swift: make navigation bar Right-to-left (rtl) with both right and left items like back

I have UIViewController with UINavigationBarDelegate delegate and I set everything's programmatically and my app is multi language so I need RTL (Right to Left) support in every section like NavigationBar. I used this approach:

if MSGlobal.setting.language.direction == .L2R
{
    navigationItem.setRightBarButtonItems(rightItems, animated: true)
}
else
{
    navigationItem.setLeftBarButtonItems(rightItems, animated: true)
}
let stackCount = navigationController!.viewControllers.count
if stackCount == 1
{
    let leftBtnItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"drawer"), landscapeImagePhone: UIImage(named:"drawer"), style: UIBarButtonItemStyle.Plain, target: self, action: "cb_drawerTapped:")
    if MSGlobal.setting.language.direction == .L2R
    {
        navigationItem.setLeftBarButtonItem(leftBtnItem, animated: true)
    }
    else
    {
        navigationItem.setRightBarButtonItem(leftBtnItem, animated: true)
    }
}
else
{
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: "cb_back:")
}

Everything's work fine in LTR language like English, But in RTL language back button not shown. My result must be like this:

LTR:   [ <      Title      [btn1...btnn]]
RTL:   [[btnn...btn1]      Title      > ]

If your goal is to have right UIBarButtonItem with back action , you can change it through Storyboard by changing Semantic to Force-Right-to-Left . or by code below:

Swift 5

inside your ViewController viewDidLoad() :

self.navigationController?.navigationBar.semanticContentAttribute = .forceRightToLeft

If You want to change navigation bar and the navigation controller flow to right to left direction you can use like:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.navigationBar.semanticContentAttribute = .forceRightToLeft
}

But you should mention that it wont change Swipe Direction , It only effect on navigationBar, If you want to change the Swipe Direction then you can use:

self.navigationController?.view.semanticContentAttribute = .forceRightToLeft

If you want to do all of them in one line and change the whole app RTL use:

UIView.appearance().semanticContentAttribute = .forceRightToLeft

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM