最近要用到類似滑動解鎖的控件,繼承UISlider重寫
- (CGRect)trackRectForBounds:(CGRect)bounds
改變Slider高度的方法坑太多,而且樣式不好看,所以用UIView自己寫了個,可自定義樣式,還沒有做太多優化,但基本不耗費太多性能。上圖~
先來看看.h文件都能實現什麼功能吧<( ̄︶ ̄)↗[GO!]
#import@class HBLockSliderView; @protocol HBLockSliderDelegate @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 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*)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