如何为UIButton的按钮文字加下划线?

Dev*_*ang 7 iphone cocoa-touch objective-c ios4

文本来自数据库.我想将它用作按钮并在按钮文本下划线.我怎样才能做到这一点?

HDd*_*per 42

在iOS 6中,NSAttributedString用于修改文本,您可以使用单个UIButton或UILabel将"NSMutableAttributedString"用于多色文本,字体,样式等.

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"The Underlined text"];

// making text property to underline text-
[titleString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];

// using text on button
[button setAttributedTitle: titleString forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)


saa*_*nib 3

为此,您可以子类化UILabel并覆盖其-drawRect方法,然后使用您自己的方法UILabel并在其上添加UIButton自定义类型。

将 UILabel 中的 drawRect 方法设置为

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBStrokeColor(context, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f);

    CGContextSetLineWidth(context, 1.0f);

    CGContextMoveToPoint(context, 0, self.bounds.size.height - 1);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height - 1);

    CGContextStrokePath(context);

    [super drawRect:rect]; 

}
Run Code Online (Sandbox Code Playgroud)