最近要用到類似滑動(dòng)解鎖的控件,繼承UISlider重寫
- (CGRect)trackRectForBounds:(CGRect)bounds
改變Slider高度的方法坑太多邓线,而且樣式不好看价匠,所以用UIView自己寫了個(gè),可自定義樣式,還沒有做太多優(yōu)化军浆,但基本不耗費(fèi)太多性能坯门。上圖~
先來看看.h文件都能實(shí)現(xiàn)什么功能吧<( ̄︶ ̄)↗[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;
/**
* 拖動(dòng)后是否返回
*/
@property (nonatomic,assign) BOOL thumbBack;
@property (nonatomic, weak) id<HBLockSliderDelegate> delegate;
/**
* 設(shè)置滑動(dòng)條進(jìn)度
* value取值0~1
*/
- (void)setSliderValue:(CGFloat)value;
/**
* 動(dòng)畫設(shè)置滑動(dòng)條進(jìn)度
*/
- (void)setSliderValue:(CGFloat)value animation:(BOOL)animation completion:(void(^)(BOOL finish))completion;
/**
* 設(shè)置滑動(dòng)條顏色
*
* @param backgroud 背景色
* @param foreground 前景色
* @param thumb 滑動(dòng)控件顏色
* @param border 邊框色
*/
- (void)setColorForBackgroud:(UIColor *)backgroud foreground:(UIColor *)foreground thumb:(UIColor *)thumb border:(UIColor *)border textColor:(UIColor *)textColor;
/**
* 設(shè)置滑動(dòng)控件的起始圖片和完成圖片(可選)
*
* @param beginImage 啟始圖片
* @param endImage 完成圖片
*/
- (void)setThumbBeginImage:(UIImage *)beginImage finishImage:(UIImage *)finishImage;
/**
* 移除圓角和邊框
*/
- (void)removeRoundCorners:(BOOL)corners border:(BOOL)border;
@end
slider由4個(gè)view疊加而成,層級(jí)依次是view(背景)->label->foregroundView->thumbImageView
@interface HBLockSliderView () {
UILabel *_label;
UIImageView *_thumbImageView;
UIView *_foregroundView;
...
}
主要的實(shí)現(xiàn)原理:拖動(dòng)thumb時(shí)微饥,改變foregroundView的尺寸,使foregroundView始終緊貼thumb古戴。通過觸摸事件來獲得touch的點(diǎn)欠橘,通過改點(diǎn)來改變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文件中定義了一些宏,如圓角允瞧,線寬和默認(rèn)顏色等简软,有需要的可以自行修改
完整的demo請(qǐng)點(diǎn)擊Github
<( ̄︶ ̄)↗歡迎star歡迎follow~