keeping a UIButton pressed(state selected/highlighted),until another button is pressed?

前端 未结 3 1360
庸人自扰
庸人自扰 2021-02-09 19:26

I have 3 buttons at the bottom of my view controller, btn1 btn2 btn3, I\'m using them instead of the tab bar as it is not possible to entirely customize a tab bar as per my requ

3条回答
  •  执笔经年
    2021-02-09 19:51

    To keep the button selected, you need to call setSelected:YES in the method that your button calls. For example:

    - (void) methodThatYourButtonCalls: (id) sender {
            [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0];
    
    
    }
    
    - (void) flipButton:(UIButton*) button {
        if(button.selected) 
            [button setSelected:NO];
        else
            [button setSelected:YES];
    
    }
    

    I know it looks a little weird calling performSelector: instead of just calling [sender setSelected:YES], but the latter never works for me, while the former does!

    In order to get the buttons to deselect when a different one is pressed, I suggest adding an instance variable that holds a pointer to the currently selected button, so when a new one is touched you can call flipButton: to deselect the old one accordingly. So now your code should read:

    add a pointer to your interface

    @interface YourViewController : UIViewController
    {
        UIButton *currentlySelectedButton;
    }
    

    and these methods to your implementation

    - (void) methodThatYourButtonCalls: (id) sender {
        UIButton *touchedButton = (UIButton*) sender;
    
        //select the touched button 
        [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0]; 
    
        if(currentlySelectedButton != nil) { //check to see if a button is selected...
            [self flipButton:currentlySelectedButton];
    
        currentlySelectedButton = touchedButton;
    }
    
    - (void) flipButton:(UIButton*) button {
        if(button.selected) 
            [button setSelected:NO];
        else
            [button setSelected:YES];
    
    }
    

提交回复
热议问题