iOS开发程序员今日看点

iOS 自定义实现滑动解锁功能

2016-09-21  本文已影响2585人  肥猫记

最近要用到类似滑动解锁的控件,继承UISlider重写- (CGRect)trackRectForBounds:(CGRect)bounds改变Slider高度的方法坑太多,而且样式不好看,所以用UIView自己写了个,可自定义样式,还没有做太多优化,但基本不耗费太多性能。上图~

HBLockSlider.gif

先来看看.h文件都能实现什么功能吧<( ̄︶ ̄)↗[GO!]

#import <UIKit/UIKit.h>
@class HBLockSliderView;
@protocol HBLockSliderDelegate <NSObject>
@optional
- (void)sliderValueChanging:(HBLockSliderView *)slider;
- (void)sliderEndValueChanged:(HBLockSliderView *)slider;
@end

@interface HBLockSliderView : UIView
@property (nonatomic, assign) CGFloat value;
@property (nonatomic, copy) NSString *text;
@property (nonatomic, strong)UIFont *font;
@property (nonatomic,strong) UIImage *thumbImage;
@property (nonatomic,strong) UIImage *finishImage;
@property (nonatomic, assign) BOOL thumbHidden;
/**
 *  拖动后是否返回
 */
@property (nonatomic,assign) BOOL thumbBack;
@property (nonatomic, weak) id<HBLockSliderDelegate> delegate;
/**
 *  设置滑动条进度
 *  value取值0~1
 */
- (void)setSliderValue:(CGFloat)value;
/**
 *  动画设置滑动条进度
 */
- (void)setSliderValue:(CGFloat)value animation:(BOOL)animation completion:(void(^)(BOOL finish))completion;
/**
 *  设置滑动条颜色
 *
 *  @param backgroud  背景色
 *  @param foreground 前景色
 *  @param thumb      滑动控件颜色
 *  @param border     边框色
 */
- (void)setColorForBackgroud:(UIColor *)backgroud foreground:(UIColor *)foreground thumb:(UIColor *)thumb border:(UIColor *)border textColor:(UIColor *)textColor;

/**
 *  设置滑动控件的起始图片和完成图片(可选)
 *
 *  @param beginImage 启始图片
 *  @param endImage   完成图片
 */
- (void)setThumbBeginImage:(UIImage *)beginImage finishImage:(UIImage *)finishImage;
/**
 *  移除圆角和边框
 */
- (void)removeRoundCorners:(BOOL)corners border:(BOOL)border;

@end

slider由4个view叠加而成,层级依次是view(背景)->label->foregroundView->thumbImageView

@interface HBLockSliderView () {
    UILabel *_label;
    UIImageView *_thumbImageView;
    UIView *_foregroundView;
    ...
}

主要的实现原理:拖动thumb时,改变foregroundView的尺寸,使foregroundView始终紧贴thumb。通过触摸事件来获得touch的点,通过改点来改变foregroundView尺寸

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self fillForeGroundViewWithPoint:point];
    ...
}

- (void)fillForeGroundViewWithPoint:(CGPoint)point{
    CGPoint p = point;
    //修正
    p.x += thunmbW/2;
    if (p.x > kSliderW) {
        p.x = kSliderW;
    }
    if (p.x < 0) {
        p.x = 0;
    }
    self.value = p.x  / kSliderW;
    _foregroundView.frame = CGRectMake(0, 0, point.x, kSliderH);
     ...
    
}

.m文件中定义了一些宏,如圆角,线宽和默认颜色等,有需要的可以自行修改
完整的demo请点击Github
<( ̄︶ ̄)↗欢迎star欢迎follow~

上一篇下一篇

猜你喜欢

热点阅读