首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用drawRect为UIButton的标签加下划线

使用drawRect为UIButton的标签加下划线
EN

Stack Overflow用户
提问于 2012-06-27 03:48:09
回答 3查看 2K关注 0票数 1

我正在尝试在UIButton中给label的文本加下划线。但它对我不起作用。我在viewDidLoad方法中的代码:

代码语言:javascript
运行
复制
    CGFloat x = 13.0f;
CGFloat y = 15.0f;
if (self.numberOfFirstButton == 0) {
    self.numberOfFirstButton = 1;
}
for (NSUInteger i = 1; i <= 5; i++) {

    for (NSUInteger j = 0; j < 10; j++) {
        UIHouseButtons *button = [[UIHouseButtons alloc] init];
        [button setFrame:CGRectMake(x+(47*j), y, 30.0f, 30.0f)];
        [button setTitle:[NSString stringWithFormat:@"%i", self.numberOfFirstButton] forState:UIControlStateNormal];
        [button drawRect:CGRectMake(x+(47*j), y, 30.0f, 30.0f)];
        [self.view addSubview:button];
        self.numberOfFirstButton++;
    }
    y += 48.0f;
}

我的drawRect方法

代码语言:javascript
运行
复制
- (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);
[super drawRect:rect];
}

视图中有我的所有按钮,但label的文本没有下划线。我哪里做错了?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-27 03:57:34

您可以从UILabel派生子类并覆盖drawRect方法:

代码语言:javascript
运行
复制
 - (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];  

}

然后在标签上放一个定时器按钮。

票数 2
EN

Stack Overflow用户

发布于 2012-06-27 03:53:48

我建议使用NSAttributedString标签。有一堆开源项目可以让这一切变得简单。两个领先的项目是:

Nimbus' NIAttributedLabel

TTTAttributedLabel

Nimbus示例:

myLabel.underlineStyle = kCTUnderlineStyleSingle;

票数 2
EN

Stack Overflow用户

发布于 2012-11-22 22:33:51

我已经创建了一个简单的UIButton子类BVUnderlineButton (基于web上其他地方的代码),您可以将其直接放入您的项目中。

它在https://github.com/benvium/BVUnderlineButton的Github上(麻省理工学院的许可证)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11214893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档