Underlining text in UIButton

后端 未结 18 1895
终归单人心
终归单人心 2020-11-29 15:56

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 pr

18条回答
  •  悲&欢浪女
    2020-11-29 16:12

    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
    

提交回复
热议问题