0
votes

In short, how can I change the color of the black button items (while maintaining control over their size)?

Longer version: I am programmatically adding a number of custom UIBarButtonItems to a UIToolbar. I'm using the solution found here so that I can control the size of the items.

While this fixes the UIBarButtonItem size issue, it does not respect tintColor like a typical UIBarButtonItem would. So I get something like this:

uitoolbar with incorrectly colored baritems

The large white item is the color I want, but not the size. This item was simply added in IB with the tintColor set to default.

The small black items are the size I want, and were added with the following code (N.B. the lines marked with // Not producing intented result):

    for e in (self.profile?.expressions)! {
        let button = UIButton()
        button.setImage(UIImage(named: "emojiph"), for: .normal)
        button.addTarget(self, action: #selector(onEmojiInsert), for: .touchUpInside)
        let barItem = UIBarButtonItem(customView: button)
        barItem.tag = e.family_expression_id
        let wConstraint = barItem.customView?.widthAnchor.constraint(equalToConstant: 32)
        wConstraint?.isActive = true
        let hConstraint = barItem.customView?.heightAnchor.constraint(equalToConstant: 32)
        hConstraint?.isActive = true

        // Not producing intented result
        button.tintColor = UIColor.white

        // Not producing intented result
        barItem.customView?.tintColor = UIColor.white

        // Not producing intented result
        barItem.tintColor = UIColor.white

        self.emojibar.items?.append(barItem)
        // Add flexible spacers
        if (e.family_expression_id < (self.profile?.expressions.count)!) {
            self.emojibar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
        }
    }

A workaround would be to provide the white image assets, but I'd prefer to find a more elegant solution if it exists.

1
Try setting: UIImage(named: "emojiph") renderingMode to template.Brandon

1 Answers

2
votes

To make the button change the color of the presented image to match the tint color then you need to initiate the button as a system type

let button = UIButton(type: .system)