Skip to content

Instantly share code, notes, and snippets.

@syxc
Last active October 31, 2015 12:51
Show Gist options
  • Save syxc/84188b5065920b389a9b to your computer and use it in GitHub Desktop.
Save syxc/84188b5065920b389a9b to your computer and use it in GitHub Desktop.
简单的开关按钮实现
//
// ToggleButton.h
// FaceDemo
//
// Created by syxc on 15/10/31.
// Copyright © 2015年 syxc. All rights reserved.
//
#import <UIKit/UIKit.h>
/*!
* 开关按钮
*/
@interface ToggleButton : UIButton
@property (assign, nonatomic, getter=isOn) BOOL on;
@property (strong, nonatomic) UIImage *offStateImage;
@property (strong, nonatomic) UIImage *onStateImage;
- (void)toggle;
@end
//
// ToggleButton.m
// FaceDemo
//
// Created by syxc on 15/10/31.
// Copyright © 2015年 syxc. All rights reserved.
//
#import "ToggleButton.h"
@interface ToggleButton ()
- (void)touchedUpInside:(UIButton *)sender;
@end
@implementation ToggleButton
@synthesize on = _on;
@synthesize offStateImage = _offStateImage;
@synthesize onStateImage = _onStateImage;
- (instancetype)init {
self = [super init];
if (self) {
[self setup];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (void)setup {
self.offStateImage = [self imageForState:UIControlStateNormal];
self.onStateImage = [self imageForState:UIControlStateSelected];
[self addTarget:self action:@selector(touchedUpInside:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)touchedUpInside:(UIButton *)sender {
[self toggle];
}
- (void)toggle {
[self setOn:!_on];
}
- (void)setOn:(BOOL)on {
_on = on;
[self setSelected:_on];
if (on) {
[self setImage:self.onStateImage forState:(UIControlStateSelected)];
} else {
[self setImage:self.offStateImage forState:(UIControlStateNormal)];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment