How to use a UIButton as a toggle switch

前端 未结 11 770
我在风中等你
我在风中等你 2020-12-02 18:44

I am using a UIButton of custom type and what I want is use it like a toggle switch with the change of image. Like when it is clicked if previously it was not in selected mo

11条回答
  •  不思量自难忘°
    2020-12-02 19:17

    In your header file add:

    IBOutlet UIButton *toggleButton;
    BOOL toggleIsOn;
    
    @property (nonatomic, retain) IBOutlet UIButton *toggleButton;
    

    In the implementation:

    - (IBACtion)toggle:(id)sender
    {
      if(toggleIsOn){
        //do anything else you want to do.
      }
      else {
        //do anything you want to do.
      }
      toggleIsOn = !toggleIsOn;
      [self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? @"on.png" :@"off.png"] forState:UIControlStateNormal];
    }
    

    then link your button with the IBActions and the IBOutlet and initialize toggleIsOn to NO.

提交回复
热议问题