任何人都可以提供代码向我展示如何在UILabel中加下划线文字吗?在Interface Builder中,我为UILabel文本加下划线,但它不起作用。
答案 0 :(得分:2)
您可以继承UILabel并在drawTextInRec中自行绘制一行
答案 1 :(得分:1)
您需要实现drawRect:
继承类的UIView
方法。
- (void)drawRect:(CGRect)rect
{
// Get the Render Context
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Measure the font size, so the line fits the text.
// Could be that "titleLabel" is something else in other classes like UILable, dont know.
// So make sure you fix it here if you are enhancing UILabel or something else..
CGSize fontSize =[self.titleLabel.text sizeWithFont:self.titleLabel.font
forWidth:self.bounds.size.width
lineBreakMode:UILineBreakModeTailTruncation];
// Get the fonts color.
const float * colors = CGColorGetComponents(self.titleLabel.textColor.CGColor);
// Sets the color to draw the line
CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0f); // Format : RGBA
// Line Width : make thinner or bigger if you want
CGContextSetLineWidth(ctx, 1.0f);
// Calculate the starting point (left) and target (right)
float fontLeft = self.titleLabel.center.x - fontSize.width/2.0;
float fontRight = self.titleLabel.center.x + fontSize.width/2.0;
// Add Move Command to point the draw cursor to the starting point
CGContextMoveToPoint(ctx, fontLeft, self.bounds.size.height - 1);
// Add Command to draw a Line
CGContextAddLineToPoint(ctx, fontRight, self.bounds.size.height - 1);
// Actually draw the line.
CGContextStrokePath(ctx);
// should be nothing, but who knows...
[super drawRect:rect];
}
采取形式iPhone Programming how to underline UILabel
您也可以继承UILabel
。请参阅belwo SO帖子,它完全相同。