after tapping the 'record' BarButtonItem I would like to keep it programmatically highlighted until the recording is over. The highlighting graphics of iOS are very good, therefor I would like to remain or set that state.
Up to now I found 'setSelected' and 'setHighlighted' but these do not work on a UIBarButtonItem. Any suggestions on how to solve this? Thank you in advance, Koen.
p.a.'s answer, converted for Xcode 9, Swift 4.
The idea is that the
.done
style highlights - or bolds, in Swift 4 - the button text.Initialize the button item in an un-highlighted state:
Toggle the button item to a highlighted state using a ternary operator, like so:
Or, alternatively, toggle the highlight state with a regular
if/else
statement like this instead:And, to set up a boolean value to check if the button item is highlighted:
Notes:
bordered
style was deprecated in iOS 8, so I used.plain
here instead. They both present the button item's text in an unhighlighted state.The
#selector
function must either be an@IBAction
, or it must be prefixed with@objc
, to avoid "Objective-C inference" issues. For example:or, if you've connected an action to the button item:
Both of these function declarations tell the compiler that they're using Objective-C-based functionality. This is required because
#selector
is an Objective-C thing under the hood, and in Swift 4 you have to state this, rather than letting the compiler infer what's going on as it has done previously.If you absolutely want to use the default graphics, you could initialize your button item as
and toggle it with
You would also need to use the style property to read the current state.
You create an outlet of this button for example
btnMoreOut
and you do:I hope this helps..Good luck :)
setSelected
andsetHighlighted
work fine on UIControls, but not UIBarButtonItems (which are not UIControls).I'd recommend using UIBarButtonItem's
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics
(documentation linked) method to change the background image to something that mimics highlighting.You can also set a custom UIView on the item which also mimics highlighting (see the
customView
property).You can try this (Swift):
Call setupInterface() in ViewDidLoad and another function in your code.
If you add a
UIBarButtonItem
with aUIButton
backing it, you can just ask for the CustomView.