【发布时间】:2011-06-23 07:59:15
【问题描述】:
如何在iphone中下划线(目标c)???
【问题讨论】:
-
什么文字?在 UILabel 中?在 UITextField 中?在 UITextView 中?直接在视图上绘制时?这不是任何人都能回答的问题。
标签: objective-c ios4 underline
如何在iphone中下划线(目标c)???
【问题讨论】:
标签: objective-c ios4 underline
UILabel 没有简单的下划线。所以有两种方法:
UIWebView,您可以使用<span style="text-decoration:underline">underlined html text<span> 为您需要的文本添加下划线。UILabel - 对于短单行标签来说这是个好主意。您应该创建一些继承UILabel 的CUILabel 类,并将@implementation 部分中的drawRect 方法替换为以下代码:`
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 0.0f/255.0f, 0.0f/255.0f, 255.0f/255.0f, 1.0f); // Your underline color
CGContextSetLineWidth(ctx, 1.0f);
UIFont *font = [UIFont systemFontOfSize:16.0f];
CGSize constraintSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
CGSize labelSize;
labelSize = [self.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, labelSize.width + 10, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
【讨论】:
除了 NR4TR 的回答之外,另一个选择是使用 CoreText。
【讨论】:
我将 NR4TR 的代码更改为更自动:
#import "UILabelUnderlined.h"
@implementation UILabelUnderlined
@synthesize underlineWidth;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.underlineWidth = 1.0f;
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat red;
CGFloat green;
CGFloat blue;
CGFloat alpha;
[self.textColor getRed:&red green:&green blue:&blue alpha:&alpha];
CGContextSetRGBStrokeColor(ctx, red, green, blue, 1.0f); // Your underline color
CGContextSetLineWidth(ctx, self.underlineWidth);
CGSize constraintSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
CGSize labelSize;
labelSize = [self.text sizeWithFont:self.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
CGContextMoveToPoint(ctx, 10, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, labelSize.width + 10, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
@end
【讨论】:
您可以在检测中使用 webview 并勾选“链接”复选框并提供 html 文本
htmlContentTxt = @"<a title="XYZ" href="http://www.XYZ.com">www.XYZ.com</a>";
[webview loadHTMLString:htmlContentTxt baseURL:nil];
【讨论】: