Monday, 1 July 2013

UIButton Or UILabel with underlined text. iOS 6.


For iOS 6 -----------

    NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] initWithString:@"ADD ANOTHER CONTACT"];

    [commentString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [commentString length])];

// Or for adding Colored text use----------
    UIColor* textColor = [UIColor blueColor];
    [commentString setAttributes:@{NSForegroundColorAttributeName:textColor,NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[commentString length])];
// Or for adding Colored text use----------

    [_addContactButton setAttributedTitle:commentString forState:UIControlStateNormal];




For Below iOS 6 -----------
Modify drawRect: function in subclass of UIButton.

UnderlinedButton.h
@interface UnderlinedButton : UIButton {

}


+ (UnderlinedButton*) underlinedButton;
@end 
UnderlinedButton.m
@implementation UnderlinedButton

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

- (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

No comments:

Post a Comment