How to use a UIButton as a toggle switch

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

    The only problem here is that you have to use 2 images to achieve toggling. Also you can't use highlighted property because of UIButton (UIControl) automatically sets this property under the hood, to be exact in touchBegan:, touchMoved:, etc. methods. The best way I offer is to simple use subclassing:

    @interface ToggleButton : UIButton
    
    @end
    
    @implementation ToggleButton
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
        [super touchesBegan:touches withEvent:event];
        self.highlighted = self.selected = !self.selected;
    }
    
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
        [super touchesMoved:touches withEvent:event];
        self.highlighted = self.selected;
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
        [super touchesEnded:touches withEvent:event];
        self.highlighted = self.selected;
    }
    
    - (void)setSelected:(BOOL)selected{
        [super setSelected:selected];
        self.highlighted = selected;
    }
    
    @end
    

    This is quite enough to make your toggle working

提交回复
热议问题