简体   繁体   中英

Swift: navigation bar item text and image

I use this code to show image and text in navigation bar item.

func barItem() {
    let button = UIButton(type: .system)
    button.setImage(UIImage(named: "trashButtonItem.png"), for: .normal)
    button.setTitle("Читать", for: .normal)
    button.sizeToFit()
        
    self.navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true);
}

In this case I have image on the left and text on the right. But I want to have image on the right and text on the left. How to do it?

You can change the button semanticContentAttribute

func barItem() {
    let button = UIButton(type: .custom)
    button.setImage(UIImage(named: "trashButtonItem.png"), for: .normal)
    button.setTitle("Читать", for: .normal)
    button.semanticContentAttribute = .forceLeftToRight
    button.sizeToFit()
        
    self.navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true);
}

You can also handle RTL

button.semanticContentAttribute = UIApplication.shared
    .userInterfaceLayoutDirection == .rightToLeft ? .forceLeftToRight : .forceRightToLeft

You need to adjust the titleEdgeInsets and the imageEdgeInsets of your UIButton.

Before:

在此处输入图像描述

After:

在此处输入图像描述

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