iosswift4font-awesomeuibarbuttonitemuibarbuttonitemstyle

bar Button Item text Will change when select in moonIcon like Font Awesome in swift 4


I used this code to using moonIcon Font like font Awesome in my app for UIBarButtonItem in navigationController

let menuButton = UIBarButtonItem(title: publicSVGAssets().menu, style: UIBarButtonItemStyle.plain, target: self, action: #selector(menuAction))
menuButton.setTitleTextAttributes(NSDictionary(dictionary: [NSAttributedStringKey.font : UIFont(name: "icomoon", size: 25)!, NSAttributedStringKey.foregroundColor : UIColor.red]) as? [NSAttributedStringKey : Any], for: [])
self.navigationItem.rightBarButtonItem = menuButton

this will working well But the problem is that when user selecting the button the Icon will change like the picture below as you see in the photo the right Bar Button Image will change to question mark But I want that Menu Image like when the button Does not selected


Solution

  • It could be something as simple as the font attribute is only being applied when the state of the button is .normal (as you specify).

    You may need to specify that all states of the button get these title text attributes applied, like so:

    let title = publicSVGAssets().menu
    let style = UIBarButtonItemStyle.plain
    let selector = #selector(menuAction)
    let menuButton = UIBarButtonItem(title: title, style: style, target: self, action: selector)
    
    let font = UIFont(name: "icomoon", size: 25)
    let attributesDictionary: [NSAttributedStringKey: Any]? = [NSAttributedStringKey.font: font!, NSAttributedStringKey.foregroundColor : UIColor.red]
    menuButton.setTitleTextAttributes(attributesDictionary, for: .normal)
    menuButton.setTitleTextAttributes(attributesDictionary, for: .selected)
    menuButton.setTitleTextAttributes(attributesDictionary, for: .highlighted)
    
    self.navigationItem.rightBarButtonItem = menuButton
    

    Tapping the button will change its state. This could be why you see it change the icon when you tap it.

    Note: if you ever need to show the button in some other state (such as disabled) you will need to assign these same title text attributes for that state as well.

    ...for example:

    menuButton.setTitleTextAttributes(attributesDictionary, for: .disabled)
    

    (Note: this is a similar answer to the one @Satish gave).