1.設置label的attributedText ,eg:
let price_attr = NSAttributedString(string: "500", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = price_attr
2.自定義label
#import <UIKit/UIKit.h>
@interface MyLabel2 : UILabel{
BOOL isWithStrikeThrough;
}
@property (nonatomic,assign)BOOL isWithStrikeThrough;
@end
//
// MyLabel2.m
// missbetterc
//
// Created by sip on 15/5/8.
// Copyright (c) 2015年 qiqugou. All rights reserved.
//
#import "MyLabel2.h"
#import "setting.h"
@implementation MyLabel2
@synthesize isWithStrikeThrough;
- (void)drawRect:(CGRect)rect
{
if (isWithStrikeThrough)
{
CGContextRef c =UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f,1.0f,1.0f,1.f};//白色
//CGFloat black[4] = {0.0f, 0.0f, 0.0f, 0.5f};//黑色
CGContextSetStrokeColor(c, red);
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 + rect.size.width, halfWayUp);//结束点
//画斜线
// CGContextMoveToPoint(c, rect.origin.x, rect.origin.y+5 );
// CGContextAddLineToPoint(c, (rect.origin.x + rect.size.width)*0.5, rect.origin.y+rect.size.height-5); //斜线
CGContextStrokePath(c);
}
[superdrawRect:rect];
}
@end
PS:也可以通过设置String属性的方式生成删除线,
例如:
NSDictionary *subStrAttribute1 =@{
NSForegroundColorAttributeName:[UIColorredColor],
NSStrikethroughStyleAttributeName:@2
};
NSDictionary *SUBsTRaTTRIBUTE2 =@{
NSForegroundColorAttributeName:[UIColorgreenColor]
};
NSString *strDisplayText3 =@"Red and Green";
NSMutableAttributedString *attributedText3 = [[NSMutableAttributedStringalloc]
initWithString:strDisplayText3 ];
[attributedText3 setAttributes:subStrAttribute1range:NSMakeRange(0,3)];
[attributedText3 setAttributes:SUBsTRaTTRIBUTE2range:NSMakeRange(8,5)];
self.myLabel.attributedText = attributedText3;