Keeping a UIButton selected after a touch

后端 未结 9 1458
后悔当初
后悔当初 2020-11-27 11:41

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

9条回答
  •  误落风尘
    2020-11-27 12:17

    I have another way ...if you don't want to use images, and you want the effect of a pressed button, You can subclass the Button and here's my code:

    in the .h File:

    @interface reservasButton : UIButton {
    
    BOOL isPressed;
    }
     @end
    

    In the .m File:

    #import 
    
    
     @implementation reservasButton
    
     -(void)setupView {  //This is for Shadow
    
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOpacity = 0.5; 
        self.layer.shadowRadius = 1;    
        self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f); //comment
        //   self.layer.borderWidth = 1;
        self.contentVerticalAlignment   = UIControlContentVerticalAlignmentCenter;
        self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
        // [self setBackgroundColor:[UIColor whiteColor]];
    
        //  self.opaque = YES;
    
    
    }
    
    -(id)initWithFrame:(CGRect)frame{
        if((self = [super initWithFrame:frame])){
            [self setupView];
        }
    
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder{
        if((self = [super initWithCoder:aDecoder])){
            [self setupView];
        }
    
        return self;
    }
    
    //Here is the important code
    
     -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    
      if (isPressed == FALSE) {
    
          self.contentEdgeInsets = UIEdgeInsetsMake(1.0,1.0,-1.0,-1.0);
          self.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
          self.layer.shadowOpacity = 0.8;
    
          [super touchesBegan:touches withEvent:event];
    
          isPressed = TRUE;
    
         }
         else {
    
             self.contentEdgeInsets = UIEdgeInsetsMake(0.0,0.0,0.0,0.0);
             self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
             self.layer.shadowOpacity = 0.5;
    
             [super touchesEnded:touches withEvent:event];
    
             isPressed = FALSE;
    
         }
    
    
     } `
    

提交回复
热议问题