UISwitch 添加 标签

给UISwitch添加一个标签。左右滑动时候出现开关标签内容。

代码:

//
//  UISwitch+JGLabel.h
//  JGSwitch
//
//  Created by sl on 15/4/11.
//  Copyright (c) 2015年 Madordie. All rights reserved.
//
//
//  说明:
//      1.给UISwitch添加开关标签
//      2.可根据需要调整标签的相关属性
//      3.类别实现,不用更改代码即可添加
//
//
//  代码出处:http://www.cnblogs.com/madordie/
//
//  思路:
//      1.找到对应View添加两个Label
//

#import <UIKit/UIKit.h>
@interface UISwitch (JGLabel)
/**
*  设置开关标题文字
*      1.根据自己需要设置字体内容、大小、字体颜色等属性。
*      2.不建议在此设置背景颜色,如需设置,调用父类方法设置。
*      3.根据需要可手动调整Label的frame,以使你的Label更加美观。
*/
#pragma mark - 标题
- (UILabel *)onTitle;
- (UILabel *)offTitle;
@end
/**
*备注:
*      1.offTitle对齐方式默认右对齐。
*      2.onTitle默认左对齐
*      3.么有了
*/
//示例代码:
/*
//初始化属性,可IB定制
UISwitch *mySwitch = [[UISwitch alloc] init];
mySwitch.center = self.view.center;
mySwitch.transform = CGAffineTransformMakeScale(2.0f, 2.0f);
[self.view addSubview:mySwitch];
//设置标题属性(当作UILabel使用)
mySwitch.offTitle.text = @"off";
mySwitch.onTitle.text  =@"on";
*/

 

//
//  UISwitch+JGLabel.m
//  JGSwitch
//
//  Created by sl on 15/4/11.
//  Copyright (c) 2015年 Madordie. All rights reserved.
//

#import "UISwitch+JGLabel.h"
#import <objc/runtime.h>
static const void *onTitleKey = &onTitleKey;
static const void *offTitleKey = &offTitleKey;
#define JGGetOnTitle                objc_getAssociatedObject(self, onTitleKey )
#define JGGetOffTitle               objc_getAssociatedObject(self, offTitleKey)
#define JGSetOnTitle(JLabel)        objc_setAssociatedObject(self, onTitleKey,  JLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
#define JGSetOffTitle(JLabel)       objc_setAssociatedObject(self, offTitleKey, JLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
@implementation UISwitch (JGLabel)
#pragma mark - getter
- (UILabel *)onTitle {
UILabel *_onTitle = JGGetOnTitle;
if (_onTitle) {
return _onTitle;
}
_onTitle = [self JGMakeLabel];
[self.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIView *view = obj;
if ([view isKindOfClass:NSClassFromString(@"_UISwitchInternalViewNeueStyle1")]) {
[view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIView *aview = obj;
if ([aview isKindOfClass:[UIImageView class]]) {
[view insertSubview:_onTitle belowSubview:aview];
}
}];
}
}];
JGSetOnTitle(_onTitle);
return _onTitle;
}
- (UILabel *)offTitle {
UILabel *_offTitle = JGGetOffTitle;
if (_offTitle) {
return _offTitle;
}
_offTitle = [self JGMakeLabel];
[self insertSubview:_offTitle atIndex:0];
[_offTitle setTextAlignment:NSTextAlignmentRight];
JGSetOffTitle(_offTitle);
return _offTitle;
}
#pragma mark - tools
- (UILabel *)JGMakeLabel {
UILabel *label = [[UILabel alloc] init];
[label setBackgroundColor:[UIColor clearColor]];
label.textColor = [UIColor blackColor];
CGRect frame = self.bounds;
frame.origin.x = 4;
frame.size.width -= 8;
label.frame = frame;
return label;
}
@end
UISwitch+JGLabel.m

http://www.cnblogs.com/madordie/p/4416111.html

 

posted @ 2015-04-11 01:56  沙漠浮萍  阅读(1098)  评论(0编辑  收藏  举报