在UIButton中加下划线的文字 [英] Underlining text in UIButton

查看:343
本文介绍了在UIButton中加下划线的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以建议如何强调一个UIButton的标题?我有一个自定义类型的UIButton,我希望标题被加下划线,但Interface Builder不提供任何选项。



在Interface Builder中,当你选择一个按钮的字体选项,它提供选项来选择None,Single,Double,Color,但是这些都没有提供按钮上的标题的任何改变。



任何帮助表示赞赏。

解决方案



UIUnderlinedButton.h

  @interface UIUnderlinedButton:UIButton {

}


+(UIUnderlinedButton *)underlinedButton;
@end

UIUnderlinedButton.m

  @implementation UIUnderlinedButton 

+(UIUnderlinedButton *)underlinedButton {
UIUnderlinedButton * button = [[UIUnderlinedButton alloc] init];
return [button autorelease];


- (void)drawRect:(CGRect)rect {
CGRect textRect = self.titleLabel.frame;

//需要将行放在descenders的顶部(负值)
CGFloat descender = self.titleLabel.font.descender;

CGContextRef contextRef = UIGraphicsGetCurrentContext();

//设置为与文本相同的颜色
CGContextSetStrokeColorWithColor(contextRef,self.titleLabel.textColor.CGColor);

CGContextMoveToPoint(contextRef,textRect.origin.x,textRect.origin.y + textRect.size.height + descender);

CGContextAddLineToPoint(contextRef,textRect.origin.x + textRect.size.width,textRect.origin.y + textRect.size.height + descender);

CGContextClosePath(contextRef);

CGContextDrawPath(contextRef,kCGPathStroke);
}


@end


Can anyone suggest how to underline the title of a UIButton ? I have a UIButton of Custom type, and I want the Title to be underlined, but the Interface Builder does not provide any option to do so.

In Interface Builder when you select the Font Option for a Button, it provides option to select None, Single, Double, Color but none of these provide any changes to the Title on the Button.

Any help appreciated.

解决方案

just needed to do this myself:

UIUnderlinedButton.h

@interface UIUnderlinedButton : UIButton {

}


+ (UIUnderlinedButton*) underlinedButton;
@end

UIUnderlinedButton.m

@implementation UIUnderlinedButton

+ (UIUnderlinedButton*) underlinedButton {
    UIUnderlinedButton* button = [[UIUnderlinedButton alloc] init];
    return [button autorelease];
}

- (void) drawRect:(CGRect)rect {
    CGRect textRect = self.titleLabel.frame;

    // need to put the line at top of descenders (negative value)
    CGFloat descender = self.titleLabel.font.descender;

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    // set to same colour as text
    CGContextSetStrokeColorWithColor(contextRef, self.titleLabel.textColor.CGColor);

    CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender);

    CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender);

    CGContextClosePath(contextRef);

    CGContextDrawPath(contextRef, kCGPathStroke);
}


@end

这篇关于在UIButton中加下划线的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆