Disabled UIToolbar appearance
Disabled UIToolbar appearance
A short tip on how to show that a UIToolbar is disabled.
Introduction
I wanted to disable a UIToolbar and then enable it later via an In App Purchase. So, you just loop over your bar buttons and disable them, right? Well, no.
1 2 3 4 5 |
for item in self.toolbarItems! { if let bb = item as? UIBarButtonItem { bb.enabled = false } } |
That does indeed disable the buttons. They are not responsive if you press them. But there is no visual cue.
So, let’s go back to the button creation code. After you create the button, you can call setTitleTextAttributes on it and specify separate NSAttributedString attributes for normal or disabled.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if let font = UIFont(name: "Whatever", size: 22.0) { var attributes = [ NSFontAttributeName : font ] var disabledAttributes = [ NSFontAttributeName : font, NSForegroundColorAttributeName : UIColor(white: 1.0, alpha: 0.5) ] var bb = UIBarButtonItem(title: glyph, style: .Plain, target: self, action: "whatever:") bb.setTitleTextAttributes(attributes, forState: UIControlState.Normal) bb.setTitleTextAttributes(disabledAttributes, forState: UIControlState.Disabled) bb.enabled = true etc. |
Great!
Doesn’t work. If you know why, let me know!
How to do it
So, I tried something different. How about setting the tint color?
I tried this for the disabled appearance.
1 |
UIToolbar.appearance().tintColor = UIColor.whiteColor() |
It does look disabled. The white isn’t exactly what I want, but it does take effect.
Actually it takes effect too well. The toolbars for every view controller are now white. That’s how the appearance proxy on the class level works.
The fix is easy enough; just set the individual button’s tintColor.
1 2 3 4 5 6 |
for item in self.toolbarItems! { if let bb = item as? UIBarButtonItem { bb.enabled = false bb.tintColor = color } } |
Now about that color. Of course you can set up your own set of colors. But let’s say you want to stay with the default system color. How do you get that? Unfortunately there is no direct way to find it. You have to get it from an unaltered UIView.
Here is how I get the default (blue) color.
1 2 3 4 |
lazy var defaultSystemTintColor:UIColor? = { var view = UIView() return view.tintColor }() |
So, to enable the toolbar:
1 2 3 4 5 6 |
for item in self.toolbarItems! { if let bb = item as? UIBarButtonItem { bb.enabled = false bb.tintColor = defaultSystemTintColor } } |
To disable the toolbar, I just set the alpha on the default color to something < 1.
1 2 3 4 5 6 7 |
var color = defaultSystemTintColor?.colorWithAlphaComponent(0.5) for item in self.toolbarItems! { if let bb = item as? UIBarButtonItem { bb.enabled = false bb.tintColor = color } } |
Summary
One easy way to set a disabled appearance is to set the tintColor property of the buttons.
There may be a way to set the appearance through NSAttributedString attributes, but that didn’t work for me.