zoukankan      html  css  js  c++  java
  • iOS创建带删除线和价钱符号的Label

    效果显示如下:

    只需要子类化Label,重写DrawRect()方法即可:

    #import "MyLabel.h"
    
    @implementation MyLabel
    
    - (instancetype)initWithFrame:(CGRect)frame{
        
        self = [super initWithFrame:frame];
        if (self) {
        
        }
        return self;
    }
    
    //重写UILabel的drawRect类
    - (void)drawRect:(CGRect)rect{
        
        // 删除线
        if (_isDelete) {
            
            UIFont *font = [UIFont systemFontOfSize:self.font.pointSize];
            CGSize size = CGSizeMake(320, 2000);
            
            // 取得高度
            CGRect labelRect = [self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
            // 取得上下文
            CGContextRef c = UIGraphicsGetCurrentContext();
            // 设置删除线颜色
            CGContextSetStrokeColorWithColor(c, [UIColor redColor].CGColor);
            // 设置线宽
            CGContextSetLineWidth(c, 1);
            CGContextBeginPath(c);
            CGFloat halfWayUp = rect.size.height/2 + rect.origin.y;
            CGContextMoveToPoint(c, rect.origin.x , halfWayUp );//开始点
            CGContextAddLineToPoint(c, rect.origin.x + labelRect.size.width, halfWayUp);//结束点
            CGContextStrokePath(c);
        }
        
        if (_isRMB){
            UIFont *font = [UIFont systemFontOfSize:self.font.pointSize];
            UIFont *fuhaofont = [UIFont systemFontOfSize:20];
            UIColor *color = [UIColor redColor];
            CGSize size = CGSizeMake(320,2000);
            CGRect labelRect = [self.text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)  attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName] context:nil];
            NSString *fuhao = @"¥";
            CGContextRef c = UIGraphicsGetCurrentContext();
            CGContextSetStrokeColorWithColor(c, [UIColor redColor].CGColor);
            [fuhao drawAtPoint:CGPointMake(rect.size.width - labelRect.size.width - 100, 5) withAttributes:@{NSFontAttributeName:fuhaofont,NSForegroundColorAttributeName:color}];
            CGContextStrokePath(c);
        }
        
        // label的字体一直显示不出来,请注意一定要调用super
        [super drawRect:rect];
        
    }
    

      

  • 相关阅读:
    少年中国说--正能量传播
    刚刚加入程序员的行列,希望通过博客的形式记录自己在这个领域的点点滴滴。同时分享自己的心得体会。
    java中的路径问题(getResourceAsStream/tomcat/maven/getContextpath)等各种路径问题
    java的jdbc
    maven的插件
    maven的仓库
    java9新特性
    java8新特性
    java的网络编程
    java的多线程juc
  • 原文地址:https://www.cnblogs.com/pengsi/p/5728889.html
Copyright © 2011-2022 走看看