自定義UISwitch,可實現(xiàn)自定義開關(guān)圖片和背景色

效果如圖所示:


自定義UISwitch

iOS7.0之后無法自定義UISwitch的圖片,而在日常的開發(fā)需求中,又不可能只有一種開關(guān)樣式,UI所設(shè)計的開關(guān)樣式千奇百怪,那么系統(tǒng)所提供的開關(guān)樣式已經(jīng)不足以滿足我們的開發(fā)需求了。所以這時候我們就需要自定義開關(guān)了。
自定義開關(guān),我們剖析下開關(guān)的結(jié)構(gòu),在系統(tǒng)的UISwitch中,我們可以看出,通過調(diào)用 onImage 或者 offImage 屬性來設(shè)置開關(guān)的圖片,但是這兩個方法在 iOS 6 之后已經(jīng)被棄用掉了。

NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UISwitch : UIControl <NSCoding>

@property(nullable, nonatomic, strong) UIColor *onTintColor NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(6_0);
@property(nullable, nonatomic, strong) UIColor *thumbTintColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;

@property(nullable, nonatomic, strong) UIImage *onImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
@property(nullable, nonatomic, strong) UIImage *offImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;

@property(nonatomic,getter=isOn) BOOL on;

- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;      // This class enforces a size appropriate for the control, and so the frame size is ignored.
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action
@end

那么,我們自定義開關(guān)所要暴露出來的屬性就要有

  • 開關(guān)開著時的圖片
  • 開關(guān)關(guān)著時的圖片
  • 開關(guān)的背景色
  • 開關(guān)的狀態(tài)
    在這里,我們可以將開關(guān)分為如圖所示兩部分結(jié)構(gòu):


    自定義開關(guān)結(jié)構(gòu)

    其中,B為開關(guān)提供底部背景色值,A為開關(guān)提供開關(guān)狀態(tài)色值,點擊開關(guān),A可以左右滑動,并改變狀態(tài)。

思路:

  • 添加點擊事件,改變自身狀態(tài)
  • 添加觀察者觀察自身狀態(tài)的改變
  • 通過判斷自身狀態(tài),顯示自身樣式

主要代碼如下所示:

@interface BKSwitch : UIControl
@property (nonatomic, assign) BOOL on;
@property (nonatomic, strong) UIView *roundView;//滑塊view
@end


@implementation BKSwitch

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self addObserver:self forKeyPath:@"isOn" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
        [self addTarget:self action:@selector(translateAni) forControlEvents:UIControlEventTouchUpInside];
        [self creatView];
    }
    return self;
}

-(void)creatView{
    self.backgroundColor = [UIColor whiteColor];
    self.clipsToBounds = YES;
    self.layer.cornerRadius = self.bounds.size.height/2;
    self.layer.borderColor = [UIColor grayColor].CGColor;
    self.layer.borderWidth = .5;
    
    self.roundView = [[UIView alloc]initWithFrame:CGRectMake(0, 1, self.bounds.size.height-2, self.bounds.size.height-2)];
    self.roundView.layer.cornerRadius = self.bounds.size.height/2;
//    self.roundView.backgroundColor = [UIColor whiteColor];
    self.roundView.userInteractionEnabled = NO;
    [self addSubview:self.roundView];
//    self.roundView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor陰影顏色
//    self.roundView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset陰影偏移,x向右偏移4,y向下偏移4,默認(0, -3),這個跟shadowRadius配合使用
//    self.roundView.layer.shadowOpacity = 0.5;//陰影透明度,默認0
//    self.roundView.layer.shadowRadius = 2;//陰影半徑,默認3
}

-(void)setOn:(BOOL)on{
    if (on) {
        self.roundView.frame = CGRectMake(self.bounds.size.width-self.roundView.bounds.size.width-1, 1,           self.bounds.size.height-2, self.bounds.size.height-2);
        self.roundView.roundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"switchOn"]];
        self.roundView.backgroundColor = OCTColorFromRGB(0xffe100);
        self.roundView.layer.borderColor = OCTColorFromRGB(0xffe100).CGColor;
    }else{
        self.roundView.frame = CGRectMake(0, 1, self.bounds.size.height-2, self.bounds.size.height-2);
        self.roundView.roundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"switchOff"]];
        self.roundView.backgroundColor = OCTColorFromRGB(0xc9c9c9);
        self.roundView.layer.borderColor = OCTColorFromRGB(0xc9c9c9).CGColor;
    }
    self.isOn = on;
}

-(BOOL)on{
    return self.isOn;
}

- (void)translateAni{
    CGRect rect = self.roundView.frame;
    [UIView animateWithDuration:0.3 animations:^{
        self.roundView.frame = rect;
    }];
    if (!self.isOn){
        rect.origin.x = self.bounds.size.width - self.roundView.bounds.size.width - 1;
    }else{
        rect.origin.x = 0;
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.roundView.frame = rect;
    }completion:^(BOOL finished) {
    }];
    self.isOn = !self.isOn;
}

//監(jiān)聽isON
//keyPath:屬性名稱
//object:被觀察的對象
//change:變化前后的值都存儲在change字典中
//context:注冊觀察者時,context傳過來的值
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"isOn"];
}

@end

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 光陰如流水, 一去不復(fù)還。 明日何其多, 人生笑談間。 即月就退休, 感慨吐心言。 韶華人生路, 教育職責擔。 從...
    王成元閱讀 286評論 3 4
  • 有時候我們會不明白,為什么一個看上去很壞的人,還有人很愛很愛他。當花千骨為了解白子畫的卜元鼎之毒不惜成為全天下的“...
    田小等閱讀 378評論 0 1
  • 《忽曉前顧后》 呼中書,花音婉, 說謀其探不饒人。 錢希處,畫墨憐, 怡型城出春已晨。 沙趣易舍錄清紗, 滴離必灑...
    春城怡景閱讀 377評論 0 22
  • 你總被人欺負,是因為錯把軟弱當成了善良。在經(jīng)濟困難時遇到借錢的朋友,你不好意思拒絕所以慷慨解囊,結(jié)果那人遲遲不肯還...
    北遙_閱讀 590評論 0 1

友情鏈接更多精彩內(nèi)容