您的位置:首页 > 产品设计 > UI/UE

UILabel,文字中间划横线

2015-11-02 11:58 465 查看
在项目中我们会有这样的需求就是在label的内容上划一个线,我们可以使用一个透明的有一条线的图片实现,但是那样那条线的颜色就是固定的了,如何灵活的画线呢?

我们可以继承系统的UILabel然后在对其添加一个划线的属性。代码如下:

#import <UIKit/UIKit.h>

/**
* UILabel  在label中划线
*/
@interface MySelfLabel : UILabel
@property(nonatomic, assign) BOOL showLine;
@property(nonatomic, assign) UIColor * showLineColor;

@end

===============================

#import "MySelfLabel.h"

#pragma mark - UILabel
@implementation MySelfLabel

- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
if (_showLine) {
if (_showLineColor) {
[_showLineColor set];  //横线的颜色设置
}else {
[[UIColor greenColor] set]; //默认 横线颜色
}

CGContextRef c = UIGraphicsGetCurrentContext();
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);//终点
CGContextStrokePath(c);
}
}

@end


在使用的时候直接调用自己写的这个label初始化 然后设置showLine这个属性,就可以实现划线的功能了,是不是很简单呢! showLineColor通过对这个属性的设置,可以改变这条横线的颜色
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: