How to use a UIButton as a toggle switch

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

    In the interface:

    @interface TransportViewController : UIViewController {
    
        UIButton *button;
    }
    @property(nonatomic, retain) UIButton *button;
    

    In the implementation:

    - (void)loadView {
    
    [super loadView];
    
        ...
    
        [self setButton:[UIButton buttonWithType:UIButtonTypeCustom]];
        [button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setImage:[UIImage imageNamed:@"image1"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"image2"] forState:UIControlStateSelected];
    }
    
    - (void) onClick:(UIButton *)sender {
    
        [sender setSelected:!sender.selected];
    }
    

提交回复
热议问题