Underlining text in UIButton

后端 未结 18 1856
终归单人心
终归单人心 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:16

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (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();
    UIColor *colr;
    // set to same colour as text
    if (self.isHighlighted || self.isSelected) {
        colr=self.titleLabel.highlightedTextColor;
    }
    else{
        colr= self.titleLabel.textColor;
    }
    CGContextSetStrokeColorWithColor(contextRef, colr.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);
    }
    //Override this to change the underline color to highlighted color
    -(void)setHighlighted:(BOOL)highlighted
    {
    [super setHighlighted:highlighted];
    // [self setNeedsDisplay];
    }
    

提交回复
热议问题