IOS——创建可重用的开关按钮
2013-07-11 23:38
459 查看
我们想要定制按钮,可以在“开”和“关”之间切换,但是UISwitch又不符合我们的设计,这时候就得自定义这样的按钮,可以通过继承UIButton来实现。
XYToggleButton.h
地址
XYToggleButton.h
#import <UIKit/UIKit.h> @interface XYToggleButton : UIButton @property (nonatomic, getter = isOn) BOOL on; @property (nonatomic, getter = isAutotoggleEnabled) BOOL autotoggleEnabled; + (id)buttonWithOnImage:(UIImage *)onImage offImage:(UIImage *)offImage highlightedImage:(UIImage *)highlightedImage; - (BOOL)toggle; @endXYToggleButton.m
#import "XYToggleButton.h" @interface XYToggleButton () @property (nonatomic, retain) UIImage *onImage; @property (nonatomic, retain) UIImage *offImage; @end @implementation XYToggleButton @synthesize onImage = _onImage; @synthesize offImage = _offImage; @synthesize on = _on; @synthesize autotoggleEnabled = _autotoggleEnabled; + (id)buttonWithOnImage:(UIImage *)onImage offImage:(UIImage *)offImage highlightedImage:(UIImage *)highlightedImage{ XYToggleButton *button; button = [XYToggleButton buttonWithType:UIButtonTypeCustom]; button.onImage = onImage; button.offImage = offImage; [button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted]; [button setBackgroundImage:offImage forState:UIControlStateNormal]; button.autotoggleEnabled = YES; return button; } - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{ [super endTrackingWithTouch:touch withEvent:event]; if (self.touchInside && self.autotoggleEnabled) { [self toggle]; } } - (BOOL)toggle{ self.on = !self.on; return self.on; } - (void)setOn:(BOOL)on{ if (_on != on) { _on = on; [self setBackgroundImage:(_on ? self.onImage : self.offImage) forState:UIControlStateNormal]; } } //添加对IB的支持 #pragma mark - initFromNib - (void)awakeFromNib{ self.autotoggleEnabled = YES; self.onImage = [self backgroundImageForState:UIControlStateSelected]; self.offImage = [self backgroundImageForState:UIControlStateNormal]; [self setBackgroundImage:nil forState:UIControlStateSelected]; } @end代码下载:
地址
相关文章推荐
- iOS 初学者关于动态按钮代码创建
- 仿ios touch按钮创建可随意拖动的悬浮按钮
- iOS开发-UIWindow的用法-创建悬浮按钮
- iOS开发——UI基础-按钮的创建和设置
- IOS 在storyboard中创建按钮,用代码控制按钮
- ios中循环按钮的创建
- iOS 分段选择控件 开关按钮 滑杆
- iOS 循环创建按钮进行点击切换颜色问题
- android仿ios开关按钮
- android基础笔记——自定义控件和视图:放ios系统开关按钮
- android仿ios开关按钮
- iOS创建不带nib文件的工程之四--在自定义view上添加按钮
- CSS---checkbox美化,ios风格的开关按钮
- 【IOS 开发学习总结-OC-43】★ios开发——UIButton(按钮)与 UISwitch(开关按钮)
- iOS-动态创建按钮
- 仿IOS Segment、搜索框、开关按钮和时间选择
- 安卓实现仿照IOS开关按钮SwitchButton
- Android自定义控件——仿ios开关按钮
- 【转】一些常见的很不错的Android开关 高仿IOS按钮开关
- ios创建开关Button