After my user clicks a button, I\'d like that button to stay pushed during the time that I perform a network operation. When the network operation is complete, I want the bu
"Everything gets better when you turn power on"
button.selected = !button.selected;
works perfectly... after I connected the outlet to the button in the Interface Builder.
You do not need to setBackgroundImage:forState:, the builder allows you to specify the background (gets resized if necessary) or/and foreground (not resizing) images.
In swift I'm doing it like the following.
I create a Subclass of UIButton
and implemented a custom property state
class ActiveButton: UIButton {
private var _active = false
var active:Bool {
set{
_active = newValue
updateState()
}
get{
return _active
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTarget(self, action: #selector(ActiveButton.touchUpInside(_:)), forControlEvents: .TouchUpInside)
}
func touchUpInside(sender:UIButton) {
active = !active
}
private func updateState() {
NSOperationQueue.mainQueue().addOperationWithBlock {
self.highlighted = self.active
}
}
}
Works perfectly for me.
I have an easier way. Just use "performSelector" with 0 delay to perform [button setHighlighted:YES]
. This will perform re-highlighting after the current runloop ends.
- (IBAction)buttonSelected:(UIButton*)sender {
NSLog(@"selected %@",sender.titleLabel.text);
[self performSelector:@selector(doHighlight:) withObject:sender afterDelay:0];
}
- (void)doHighlight:(UIButton*)b {
[b setHighlighted:YES];
}