Reputation: 35
This is quite frustrating and I searched a LOT to no avail.
I have one button. When it is pressed it calls a method that performs a network action (NSURLRequest).
The button should do the following:
The problem is the button is STAYING in the highlighted/pressed state throughout the request. I have attached code I currently have below.
For the Button:
[myButton setBackgroundImage:[UIImage imageNamed:@"defaultbutton"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"pressedbutton"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabledbutton"] forState:(UIControlStateDisabled|UIControlStateSelected)];
[squishButton addTarget:self action:@selector(reqMethod) forControlEvents:UIControlEventTouchUpInside];
In the method at the start of the request:
-(void)reqMethod {
NSLog(@"Starting request..");
[myButton setHighlighted:NO];
[myButton setEnabled:NO];
[myButton setSelected:YES];
When the request completes it hides the normal button and shows a reset button which works fine.
Upvotes: 1
Views: 1638
Reputation: 385
Why dont you do network operation on background thread :
- (IBAction)buttonPressed:(UIButton *)button
{
[NSThread detachNewThreadSelector:@selector(doSomeNetworkStuff) toTarget:self withObject:nil];
}
Upvotes: 1
Reputation: 146
You should have a view at multithreading documentation. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html
If you want a piece of code I think that this could be useful
[myButton setBackgroundImage:[UIImage imageNamed:@"defaultbutton"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"pressedbutton"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabledbutton"] forState:(UIControlStateDisabled|UIControlStateSelected)];
[squishButton addTarget:self action:@selector(reqMethod) forControlEvents:UIControlEventTouchUpInside];
dispatch_async(dispatch_get_global_queue(0, 0),
^{
//Your request
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(@"Starting request..");
[myButton setHighlighted:NO];
[myButton setEnabled:NO];
[myButton setSelected:YES];
});
});
Upvotes: 2
Reputation: 11320
This will keep the button highlighted when you press it for the first time (you can alter it to work with images). If you press it again, it will become unhighlighted. (I know the syntax looks weird, just try it...it works)
@property (nonatomic) BOOL buttonHighlighted
// IBAction called when button pressed the first time
- (IBAction)buttonPressed:(UIButton *)button
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if(self.buttonHighlighted)
{
button.highlighted = NO;
self.buttonHighlighted = NO;
}
else
{
button.highlighted = YES;
self.buttonHighlighted = YES;
//Fire request method
}
}];
}
Now, just call this method again when your request is finished.
Upvotes: 0