本文章主要介绍了iOS 刻度尺、iOS 测量尺、iOS开发可移动的尺子、纯代码实现,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!

iOS实现刻度尺,可移动刻度尺,并取得当前对应的刻度值。

本文章,技术意义不大,主要是我想写个文章让特定的人知道我做过iOS开发;

这是以前项目里的代码,直接拿出来!

要做的功能如图:

下面是代码:

 KADRuler.h

#import <UIKit/UIKit.h> 
 
@interface KADRuler : UIView 
 
-(instancetype)initWithFrame:(CGRect)frame fromNumber:(NSInteger)fromNum toNumber:(NSInteger)toNum; 
///左边或者右边的空白 
@property(nonatomic, assign, readonly)CGFloat sideSpace; 
///根据刻度值取它的偏移 
-(CGFloat)getScaleOffsetByNumber:(NSInteger)number; 
///根据偏移取对应的刻度值 
-(NSInteger)getNumberByOffset:(CGFloat)offsetX; 
@end

 KADRuler.m

#import "KADRuler.h" 
 
@interface KADRuler() 
{ 
    NSInteger startNum, endNum; 
    CGFloat space, lrSpace; 
} 
@end 
@implementation KADRuler 
 
-(instancetype)init 
{ 
    CGRect frame = CGRectMake(0, 0, W_WIDTH, 50); 
    return [self initWithFrame:frame]; 
} 
 
-(instancetype)initWithFrame:(CGRect)frame 
{ 
    return [self initWithFrame:frame fromNumber:0 toNumber:100]; 
} 
 
-(instancetype)initWithFrame:(CGRect)frame fromNumber:(NSInteger)fromNum toNumber:(NSInteger)toNum 
{ 
    space = 8.0; 
    lrSpace = space*3; 
    startNum = fromNum; 
    endNum = toNum; 
    if (endNum<startNum) { 
        startNum = 0; 
        endNum = 100; 
    } 
    if(frame.size.height<=0){ frame.size.height = 50; } 
    frame.size.width = (endNum-startNum)*space + lrSpace*2; 
    self = [super initWithFrame:frame]; 
    if (self) { 
        self.backgroundColor = [UIColor whiteColor]; 
    } 
    return self; 
} 
 
-(CGFloat)sideSpace 
{ 
    return lrSpace; 
} 
 
-(CGFloat)getScaleOffsetByNumber:(NSInteger)number 
{ 
    if (number<startNum) { 
        return 0; 
    } 
    CGFloat x = lrSpace + space*(number-startNum); 
    return x; 
} 
 
-(NSInteger)getNumberByOffset:(CGFloat)offsetX 
{ 
    offsetX += 0.05; //增加偏移补偿量,如不增加,则在4/5/5s/6Plus会有边界值显示错误bug 
    NSInteger num = (offsetX - lrSpace)/space + startNum; 
    return num; 
} 
 
-(void)drawRect:(CGRect)rect 
{ 
    CGFloat r,g,b,a; 
    UIColor *color = [UIColor colorWithRgbToUIColor:@"898989"]; 
    [color getRed:&r green:&g blue:&b alpha:&a]; 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    // 设置线的粗细 
    CGContextSetLineWidth(context, 1.0); 
    CGFloat x = lrSpace, y=0; 
    //设置字体 
    UIFont *font = [UIFont systemFontOfSize:13.0]; 
    for (long i=startNum; i<=endNum; i++) { 
        // 设置线的颜色及透明度 
        CGContextSetRGBStrokeColor(context, r, g, b, a); 
        // 开始点 
        CGContextMoveToPoint(context, x, 0.0); 
        //结束点 
        y = i%5==0?25:15; 
        CGContextAddLineToPoint(context, x, y); //22 
        //开始一条线 
        CGContextStrokePath(context); 
        // 
        if (i%10==0) { 
            //设置矩形填充颜色:红色 
            CGContextSetRGBFillColor (context, 34.0/255.0, 34.0/255.0, 34.0/255.0, 1.0); 
            //在指定的矩形区域内画文字 
            NSString *num = [NSString stringWithFormat:@"%ld", i]; 
            CGSize size = [num sizeWithFont:font]; 
            [num drawInRect:CGRectMake(x-size.width/2-0.5, y+3, size.width, size.height) withFont:font]; 
        } 
        // 
        x += space; 
    } 
} 
 
 
@end

 KADRulerControl.h

#import "KADUIControl.h" 
 
@interface KADRulerControl : KADUIControl 
///自定义范围初始化 
-(instancetype)initWithFrame:(CGRect)frame fromNumber:(NSInteger)fromNum toNumber:(NSInteger)toNum; 
///当前刻度值 
@property (nonatomic, assign)NSInteger SelectedScale; 
///最小可用刻度 
@property(nonatomic, assign)NSInteger minNumber; 
///最大可用刻度 
@property(nonatomic, assign)NSInteger maxNumber; 
@end

KADRulerControl.m

#import "KADRulerControl.h" 
#import "KADRuler.h" 
 
@interface KADRulerControl()<UIScrollViewDelegate> 
{ 
    UIScrollView *_scro; 
    KADRuler *ruler; 
    NSInteger selectedNumber; 
    NSInteger startNum, endNum; 
    BOOL isBusy; 
} 
@end 
@implementation KADRulerControl 
 
-(instancetype)init 
{ 
    CGRect frame = CGRectMake(0, 0, W_WIDTH, 50); 
    return [self initWithFrame:frame]; 
} 
 
-(instancetype)initWithFrame:(CGRect)frame 
{ 
    return [self initWithFrame:frame fromNumber:0 toNumber:100]; 
} 
 
-(instancetype)initWithFrame:(CGRect)frame fromNumber:(NSInteger)fromNum toNumber:(NSInteger)toNum 
{ 
    if (toNum<fromNum) { 
        fromNum = 0; 
        toNum = 100; 
    } 
    self = [super initWithFrame:frame]; 
    if (self) { 
        self.minNumber = fromNum; 
        self.maxNumber = toNum; 
        _scro = [[UIScrollView alloc] init]; 
        _scro.frame = self.bounds; 
        _scro.bounces = NO; 
        _scro.showsHorizontalScrollIndicator = NO; 
        _scro.showsVerticalScrollIndicator = NO; 
        _scro.delegate = self; 
        _scro.backgroundColor = [UIColor clearColor]; 
        _scro.pagingEnabled = NO; 
        [self addSubview:_scro]; 
        // 
        startNum = fromNum-50; 
        endNum = toNum+50; 
        ruler = [[KADRuler alloc]initWithFrame:frame fromNumber:startNum toNumber:endNum]; 
        [_scro addSubview:ruler marginLeft:0 marginTop:0]; 
        [_scro setContentSizeWidth:ruler.width]; 
        // 
        [self addSubview:[self createHLine] marginTop:0]; 
        selectedNumber = (toNum-fromNum)/2; 
        self.SelectedScale = selectedNumber; 
    } 
    return self; 
} 
 
-(void)scrollViewDidScroll:(UIScrollView *)scrollView 
{ 
    CGFloat offsetX = scrollView.contentOffset.x; 
    selectedNumber = [ruler getNumberByOffset:offsetX + (_scro.width/2.0)]; 
    //限制最小和最大值 
    if(selectedNumber<self.minNumber){ 
        scrollView.decelerationRate = 0.0; 
        scrollView.scrollEnabled = NO; 
        CGFloat x = [ruler getScaleOffsetByNumber:self.minNumber]; 
        x -= (_scro.width/2.0); 
        CGPoint offset = scrollView.contentOffset; 
        offset.x = x; 
        [scrollView setContentOffset:offset animated:NO]; 
        scrollView.scrollEnabled = YES; 
        scrollView.decelerationRate = UIScrollViewDecelerationRateNormal; 
    }else if(selectedNumber>self.maxNumber){ 
        scrollView.decelerationRate = 0.0; 
        scrollView.scrollEnabled = NO; 
        CGFloat x = [ruler getScaleOffsetByNumber:self.maxNumber]; 
        x -= (_scro.width/2.0); 
        CGPoint offset = scrollView.contentOffset; 
        offset.x = x; 
        //scrollView.contentOffset = offset;//不能马上停止 
        [scrollView setContentOffset:offset animated:NO];//可马上停止 
        scrollView.scrollEnabled = YES; 
        scrollView.decelerationRate = UIScrollViewDecelerationRateNormal; 
    } 
    [self ExecActionBlock:self andTag:selectedNumber andData:nil]; 
} 
 
 
-(NSInteger)SelectedScale 
{ 
    return selectedNumber; 
} 
 
-(void)setSelectedScale:(NSInteger)SelectedScale 
{ 
    selectedNumber = SelectedScale; 
    CGFloat offsetX = [ruler getScaleOffsetByNumber:selectedNumber]; 
    offsetX -= (_scro.width/2.0); 
    [_scro setContentOffsetX:offsetX]; 
} 
 
-(UIView*)createHLine 
{ 
    UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 58)]; 
    v.backgroundColor = [UIColor colorWithRgbToUIColor:@"fc2d2d"]; 
    return v; 
} 
 
/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 
    // Drawing code 
} 
*/ 
 
@end 

KADBMICalculatorVC.m

// 
//  KADBMICalculatorVC.m 
//  KADOnlinePharmacies 
// 
//  Created by envon on 15-4-25. 
//  Copyright (c) 2015年 360KAD. All rights reserved. 
// 
 
#import "KADBMICalculatorVC.h" 
#import "KADRulerControl.h" 
#import "KADBMIResultVC.h" 
#import "KADGuidePageService.h" 
 
@interface KADBMICalculatorVC ()<UIScrollViewDelegate> 
{ 
    CGFloat startY; 
    UIScrollView *_scro; 
    UILabel *labN2,*labN1; 
    KADRulerControl *ruler1,*ruler2; 
} 
@end 
 
@implementation KADBMICalculatorVC 
 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    startY = [super getStartY]; 
    self.view.backgroundColor = [UIColor colorWithRgbToUIColor:@"eeeeee"]; 
    KADNavigationBar *navBar = [super setNavigationBarWithTitle:@"BMI计算器" andHasBackButton:YES]; 
    [navBar.contentView addSubview:[self createLine] marginLeft:0 marginBottom:0]; 
    __weak KADBMICalculatorVC *me = self; 
    CGFloat space = Fit750(20); 
     
    //=========== 右上角“更多”选项按钮 
    UIButton *rightBarBtn = [super createRMenuWithTag:222]; 
    rightBarBtn.backgroundColor = [UIColor clearColor]; 
    [navBar.contentView addSubview:rightBarBtn]; 
     
    _scro = [[UIScrollView alloc] init]; 
    _scro.frame = CGRectMake(0, startY, W_WIDTH, self.view.height-startY); 
    _scro.bounces = NO; 
    _scro.showsHorizontalScrollIndicator = NO; 
    _scro.showsVerticalScrollIndicator = NO; 
    _scro.delegate = self; 
    _scro.backgroundColor = [UIColor clearColor]; 
    [self.view addSubview:_scro]; 
     
    /** 
     * 
     * 身高 
     */ 
    /** 默认身高 */ 
    NSInteger defaultHeight = 170; 
    UIView *v1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Fit750(750), Fit750(290))]; 
    v1.backgroundColor = [UIColor whiteColor]; 
    [_scro addSubview:v1 marginLeft:0 marginTop:space]; 
     
    ruler1 = [[KADRulerControl alloc]initWithFrame:CGRectMake(0, 0, W_WIDTH-2*space, Fit750(180)) fromNumber:30 toNumber:300]; 
    ruler1.layer.borderColor = [UIColor colorWithRgbToUIColor:@"cbcbcb"].CGColor; 
    ruler1.layer.borderWidth = KAD_ONE_POINT_WIDTH; 
    ruler1.SelectedScale = defaultHeight; 
    [ruler1 setActionBlock:^(id handle, NSInteger tag, id data) { 
        [me setN1:tag]; 
    }]; 
    [v1 addSubview:ruler1 marginLeft:space marginBottom:space]; 
    // 
    UILabel *lab11 = [UILabel labelWithFrame:CGRectZero text:@"身高" fontSize:14 textRgbColor:@"222222" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    UILabel *lab12 = [UILabel labelWithFrame:CGRectZero text:@"CM" fontSize:14 textRgbColor:@"222222" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    [lab11 autoSizeWithFont]; [lab12 autoSizeWithFont]; 
    [v1 addSubview:lab11 marginLeft:space marginTop:Fit750(44)]; 
    [v1 addSubview:lab12 marginRight:space marginTop:Fit750(44)]; 
    // 
    labN1 = [UILabel labelWithFrame:CGRectZero text:[NSString stringWithFormat:@"%zd",defaultHeight] fontSize:14 textRgbColor:@"2d8ff3" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    labN1.font = [UIFont boldSystemFontOfSize:16]; 
    [labN1 autoSizeWithFont]; 
    [v1 addSubview:labN1 marginTop:Fit750(40)]; 
     
    /** 
     * 
     * 体重 
     */ 
    /** 默认体重 */ 
    NSInteger defaultWeight = 70; 
    UIView *v2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Fit750(750), Fit750(290))]; 
    v2.backgroundColor = [UIColor whiteColor]; 
    [_scro addSubview:v2 atBottomFrame:v1.frame top:space left:0]; 
     
    ruler2 = [[KADRulerControl alloc]initWithFrame:CGRectMake(0, 0, W_WIDTH-2*space, Fit750(180)) fromNumber:0 toNumber:300]; 
    ruler2.layer.borderColor = [UIColor colorWithRgbToUIColor:@"cbcbcb"].CGColor; 
    ruler2.layer.borderWidth = KAD_ONE_POINT_WIDTH; 
    ruler2.SelectedScale = defaultWeight; 
    [ruler2 setActionBlock:^(id handle, NSInteger tag, id data) { 
        [me setN2:tag]; 
    }]; 
    [v2 addSubview:ruler2 marginLeft:space marginBottom:space]; 
    // 
    UILabel *lab21 = [UILabel labelWithFrame:CGRectZero text:@"体重" fontSize:14 textRgbColor:@"222222" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    UILabel *lab22 = [UILabel labelWithFrame:CGRectZero text:@"KG" fontSize:14 textRgbColor:@"222222" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    [lab21 autoSizeWithFont]; [lab22 autoSizeWithFont]; 
    [v2 addSubview:lab21 marginLeft:space marginTop:Fit750(44)]; 
    [v2 addSubview:lab22 marginRight:space marginTop:Fit750(44)]; 
    // 
    labN2 = [UILabel labelWithFrame:CGRectZero text:[NSString stringWithFormat:@"%zd",defaultWeight] fontSize:14 textRgbColor:@"2d8ff3" bgRgbColor:@"clear" align:NSTextAlignmentCenter]; 
    labN2.font = [UIFont boldSystemFontOfSize:16]; 
    [labN2 autoSizeWithFont]; 
    [v2 addSubview:labN2 marginTop:Fit750(40)]; 
     
    /** 
     * 
     *  计算按钮 
     */ 
     
    UIButton *btnCount = [UIButton buttonWithFrame:CGRectMake(0, 0,Fit750(709) ,Fit750(88)) Title:@"马上计算" titleFont:[UIFont systemFontOfSize:Fit320(15)] titleColor:[UIColor whiteColor] bgColor:[UIColor colorWithRgbToUIColor:@"2d8ff3"] borderWith:0 borderColor:[UIColor clearColor] cornerRadius:4]; 
    [btnCount addTarget:self action:@selector(tapCount) forControlEvents:UIControlEventTouchUpInside]; 
    [_scro addSubview:btnCount atBottomFrame:v2.frame top:space]; 
     
    /** 
     * 
     *  底部提示框 
     */ 
     
    UIView *tips = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Fit750(709), 80)]; 
    tips.backgroundColor = [UIColor colorWithRgbToUIColor:@"fafafa"]; 
    tips.layer.cornerRadius = 3; 
    [_scro addSubview:tips atBottomFrame:btnCount.frame top:space left:0]; 
     
    NSString *str = @"<font color='#898989'><b>BMI科普:</b><br>BMI指数(身体质量指数,简称体质指数又称体重指数,英文为Body Mass Index,简称BMI),是用体重公斤数除以身高米数平方得出的数字,是目前国际上常用的衡量人体胖瘦程度以及是否健康的一个标准。备注:BMI计算适用于成人(18岁以上),不包括运动员及孕产妇。</font>"; 
    RTLabel *rtLabel = [[RTLabel alloc] initWithFrame:CGRectMake( 0,0 ,tips.width-space*2, 0)]; 
//    rtLabel.lineSpacing = Fit320(8); 
    [rtLabel setText:str]; 
    rtLabel.font = [UIFont systemFontOfSize:Fit320(12)]; 
    [rtLabel fitSize]; 
    [tips addSubview:rtLabel marginLeft:space marginTop:space]; 
     
    [tips setHeight:CGRectGetMaxY(rtLabel.frame) + space]; 
    [_scro setContentSizeHeight:CGRectGetMaxY(tips.frame) + 20]; 
} 
 
-(void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
    //引导页 
    [KADGuidePageService showInViewController:self]; 
} 
 
///点击计算按钮 
-(void)tapCount 
{ 
    NSInteger num1 = ruler1.SelectedScale;//身高 
    NSInteger num2 = ruler2.SelectedScale;//体重 
//=========== 测试用提醒 
//    [self alertShow:[NSString stringWithFormat:@"身高:%ld, 体重:%ld",num1, num2]]; 
    KADBMIResultVC *bmiResult = [[KADBMIResultVC alloc]init]; 
    bmiResult.num1 = num1; 
    bmiResult.num2 = num2; 
    bmiResult.backAnimated = YES; 
    bmiResult.hidesBottomBarWhenPushed = YES; 
    [self.navigationController pushViewController:bmiResult animated:YES]; 
} 
 
-(void)setN1:(NSInteger)number 
{ 
    CGPoint p = labN1.center; 
    labN1.text = [NSString stringWithFormat:@"%ld", (long)number]; 
    [labN1 autoSizeWithFont]; 
    labN1.center = p; 
} 
 
-(void)setN2:(NSInteger)number 
{ 
    CGPoint p = labN2.center; 
    labN2.text = [NSString stringWithFormat:@"%ld", (long)number]; 
    [labN2 autoSizeWithFont]; 
    labN2.center = p; 
} 
 
-(UIView*)createLine 
{ 
    UIView *imgV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Fit1125(1125), KAD_ONE_POINT_WIDTH)]; 
    imgV.backgroundColor = [UIColor colorWithRgbToUIColor:@"cbcbcb"]; 
    return imgV; 
} 
 
- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
 
/* 
#pragma mark - Navigation 
 
// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 
 
@end

-----------------------------------END


发布评论
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

iOS判断消息推送开关详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。