你可以從的UILabel子類,並重寫的drawRect方法:
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f); // RGBA
CGContextSetLineWidth(ctx, 1.0f);
CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
CGContextAddLineToPoint(ctx, self.bounds.size.width, self.bounds.size.height - 1);
CGContextStrokePath(ctx);
[super drawRect:rect];
}
UPD:
作爲iOS 6中蘋果增加NSAttributedString對的UILabel支持,所以現在它更容易和作品多行:
NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:@"Test string"
attributes:underlineAttribute];
如果你仍然希望支持iOS 4和iOS 5,我會建議結束使用TTTAttributedLabel而不是手動標註下劃線標籤。但是,如果您需要強調單行UILabel並且不想使用第三方組件,上面的代碼仍然可以解決問題。
看看[我這篇文章(http://davidjhinson.wordpress.com/2009/11/26/underline-text-on-the-iphone/) – Casebash 2010-10-07 03:39:26