2012-07-20 144 views
1

這是非常令人沮喪的,我搜索了很多無濟於事。UIButton保持突出顯示時按下

我有一個按鈕。當它被按下時,它會調用執行網絡操作的方法(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]; 

當請求完成它隱藏了普通按鈕和示出了復位按鈕的正常工作。

回答

1

您應該看到多線程文檔。 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]; 
        }); 
       }); 
+0

謝謝你,這個工作出色。 – element6 2012-07-21 14:29:40

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

現在,當您的請求完成只需再次調用此方法。

1

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

    [NSThread detachNewThreadSelector:@selector(doSomeNetworkStuff) toTarget:self withObject:nil]; 
}