How to use a UIButton as a toggle switch

前端 未结 11 769
我在风中等你
我在风中等你 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 18:59

    I made this class, changing the class to PGToggleButton in the Interface builder will do it. It uses the images for Default and Highlighted state, and has a public property to get/set the actual state.

    PGToggleButton.h

    @interface PGToggleButton : UIButton
    
    @property (nonatomic, getter=isOn) BOOL on;
    -(void)toggle;
    
    @end
    

    PGToggleButton.m

    #import "PGToggleButton.h"
    
    
    @interface PGToggleButton ()
    @property (nonatomic, strong) UIImage *offStateImage;
    @property (nonatomic, strong) UIImage *onStateImage;
    -(void)touchedUpInside:(UIButton*) sender;
    @end
    
    
    @implementation PGToggleButton
    @synthesize on = _on;
    @synthesize offStateImage = _offStateImage;
    @synthesize onStateImage = _onStateImage;
    
    -(void)awakeFromNib
    {
        [super awakeFromNib];
    
        self.offStateImage = [self imageForState:UIControlStateNormal];
        self.onStateImage = [self imageForState:UIControlStateHighlighted];
    
        [self addTarget:self
                 action:@selector(touchedUpInside:)
              forControlEvents:UIControlEventTouchUpInside];
    }
    
    -(void)touchedUpInside:(UIButton*) sender
    { [self toggle]; }
    
    -(void)toggle
    { self.on = toggle(_on); }
    
    -(void)setOn:(BOOL) on
    {
        _on = on;
    
        if (on)
            [self setImage:self.onStateImage forState:(UIControlStateNormal)];
        else
            [self setImage:self.offStateImage forState:(UIControlStateNormal)];
    }
    
    @end
    

提交回复
热议问题