ios 删除线的obj-c实现和swift实现

删除线,有几种实现思路
一种是用富文本实现
一种是继承uilabel,重写draw方法,画出来
一种是用分类(swift用拓展)实现
…..

这里写图片描述

在这里我觉得画出来是最好看的,所以,我采用了第二种,画出来

obj-c:

#import <UIKit/UIKit.h>

@interface StrickoutLabel : UILabel

@end
#import "StrickoutLabel.h"

@implementation StrickoutLabel

-(void)drawRect:(CGRect)rect{
//    // 调用super的drawRect:方法,会按照父类绘制label的文字
    [super drawRect:rect];

    /**
     * 因为是在xib布局,利用的是约束,所以不能用self.frame.size.height得到高度,这个值是没有值的,
     * 这时候需要用CGRectGetHeight(self.frame)来得到高度。
     */

    // 1 获取上下文
    CGContextRef context = UIGraphicsGetCurrentContext();

    // 2 设置线条颜色
    [self.textColor setStroke];

    // 3 线的起点
    CGFloat y = CGRectGetHeight(self.frame) /2;
    CGContextMoveToPoint(context, 0, y);
    // 4 短标题,根据字体确定宽度
    CGSize size = [self.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil]];
    // 5 线的终点 所以换行出问题了
    CGContextAddLineToPoint(context, size.width, y);
    // 6 最后渲染上去
    CGContextStrokePath(context);


}

@end

相应的,转换成swift代码的时候,代码如下

//
//  StrickoutLabel.swift
//  ego
//
//  Created by xihao on 2017/8/25.
//  Copyright © 2017年 yidont. All rights reserved.
//

import Foundation
import UIKit

class StrickoutLabel2 :UILabel{

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

//        // 1 获取上下文
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        
//        // 2 设置线条颜色
//        [self.textColor setStroke];
//        
//        // 3 线的起点
//        CGFloat y = CGRectGetHeight(self.frame) /2;
//        CGContextMoveToPoint(context, 0, y);
//        // 4 短标题,根据字体确定宽度
//        CGSize size = [self.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil]];
//        // 5 线的终点 所以换行出问题了
//        CGContextAddLineToPoint(context, size.width, y);
//        // 6 最后渲染上去
//        CGContextStrokePath(context);

        let context = UIGraphicsGetCurrentContext()!

        self.textColor.setStroke()

        let y : CGFloat = self.frame.height/2

        context.move(to: CGPoint.init(x: 0, y: y))

        let size = (self.text! as NSString).size(attributes: [NSFontAttributeName:self.font])

        context.addLine(to: CGPoint.init(x: size.width, y: y))

        context.strokePath()

    }

}

以上代码测试过了,没问题

QQ:361561789
有事可以直接加Q联系

猜你喜欢

转载自blog.csdn.net/chen_xi_hao/article/details/77878118