1

UIButton でラベルのテキストに下線を引こうとしています。しかし、それは私にはうまくいきませんでした。メソッド内の私のコードviewDidLoad:

    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方法

- (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];
}

すべてのボタンが表示されていますが、ラベルのテキストに下線が引かれていません。私が間違っていることは何ですか?

4

3 に答える 3

2

NSAttributedString ラベルを使用することをお勧めします。これを簡単にするオープンソースプロジェクトがたくさんあります。主なプロジェクトは次の 2 つです。

Nimbus の NIAttributedLabel
TTTAttributedLabel

ニンバスの例:

myLabel.underlineStyle = kCTUnderlineStyleSingle;

于 2012-06-26T19:53:48.317 に答える
2

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];  

}

次に、そのラベルの上にカスタム ボタンを配置します。

于 2012-06-26T19:57:33.510 に答える
0

プロジェクトに直接ドロップできるシンプルな UIButton サブクラス BVUnderlineButton (Web 上の他の場所にある他のコードに基づく) を作成しました。

https://github.com/benvium/BVUnderlineButton (MIT ライセンス)の Github にあります。

于 2012-11-22T14:33:50.733 に答える