1

这非常令人沮丧,我搜索了很多无济于事。

我有一个按钮。当它被按下时,它会调用一个执行网络操作(NSURLRequest)的方法。

该按钮应执行以下操作:

  • 按下时:显示按下状态图像,触发请求方法
  • 按下后:显示按钮的禁用状态,直到方法完成请求

问题是按钮在整个请求过程中一直处于突出显示/按下状态。我附上了我目前在下面的代码。

对于按钮:

[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];

在请求开始的方法中:

-(void)reqMethod {
NSLog(@"Starting request..");
[myButton setHighlighted:NO];
[myButton setEnabled:NO];
[myButton setSelected:YES];

当请求完成时,它会隐藏普通按钮并显示一个可以正常工作的重置按钮。

4

3 回答 3

2

您应该查看多线程文档。 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html

如果您想要一段代码,我认为这可能很有用

[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];  
                     });
                });
于 2012-07-20T15:50:07.430 回答
1

为什么不在后台线程上进行网络操作:

- (IBAction)buttonPressed:(UIButton *)button 
{

    [NSThread detachNewThreadSelector:@selector(doSomeNetworkStuff) toTarget:self    withObject:nil];
}
于 2012-07-20T19:01:05.053 回答
0

当您第一次按下它时,这将使按钮保持突出显示(您可以更改它以处理图像)。如果再次按下它,它将变得不突出。(我知道语法看起来很奇怪,试试吧……它有效)

@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
        }
    }];
}

现在,只需在您的请求完成后再次调用此方法。

于 2012-07-20T15:48:06.743 回答