自定义Switch控件

 MySwtch.h文件

#import <UIKit/UIKit.h>

 

//@class MySwich;

//

//@protocol MyswichDaget <NSObject>

//

//- (void)didClick:(MySwich*)sender;

//

//@end

 

 

@interface MySwich : UIView

{

    UIView *_xiaoview;

    void(^_didclick)(MySwich *sender);

}

@property (nonatomic,assign)BOOL on;

//@property (nonatomic)id<MyswichDaget>daget;

@property (nonatomic,assign)void (^didclick)(MySwich *sender);

 

@end

 

 

 

MySwtch.m文件

#import "MySwich.h"

 

@implementation MySwich

 

-(instancetype)initWithFrame:(CGRect)frame

{

    self=[super initWithFrame:frame];

    if (self) {

        _xiaoview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width/2, frame.size.height)];

        _xiaoview.backgroundColor=[UIColor redColor];

        [self addSubview:_xiaoview];

    }

    return self;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [UIView animateWithDuration:0.4 animations:^{\

        if (self.on) {

            self.on=NO;

            _xiaoview.frame=CGRectMake(0, 0, self.frame.size.width/2, self.frame.size.height);

//            _xiaoview.backgroundColor=[UIColor greenColor];

            self.backgroundColor=[UIColor grayColor];

        }

        else

        {

            self.on=YES;

            _xiaoview.frame=CGRectMake(self.frame.size.width/2, 0, self.frame.size.width/2, self.frame.size.height);

//            _xiaoview.backgroundColor=[UIColor redColor];

            self.backgroundColor=[UIColor greenColor];

 

        }

    } completion:^(BOOL finished) {

//        if (_daget&&[_daget respondsToSelector:@selector(didClick:)]) {

//            [_daget didClick:self];

        if (_didclick) {

            _didclick(self);

        }

        

    }];

}

 

- (void)setDidclick:(void (^)(MySwich *))didclick

{

    _didclick=didclick;

}

 

 

- (void (^)(MySwich *))didclick;

{

    return _didclick;

}

@end

 

 

 

posted on 2014-10-16 21:27  陈丰波  阅读(179)  评论(0编辑  收藏  举报