8

The text is coming form a database. I would like to use it for a button and underline the text of the button. How can I do that?

fabian789
  • 8,348
  • 4
  • 45
  • 91
Devang
  • 11,258
  • 13
  • 62
  • 100

4 Answers4

44

In iOS 6, NSAttributedString is used modifying the text, you can use "NSMutableAttributedString" for multi color text, font, style, etc using single UIButton or UILabel.

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:@"The Underlined text"];

// making text property to underline text-
[titleString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [titleString length])];

// using text on button
[button setAttributedTitle: titleString forState:UIControlStateNormal];
HDdeveloper
  • 4,396
  • 6
  • 40
  • 65
3

For this you can subclass UILabel and overwrite its -drawRect method and then use your own UILabel and add a UIButton over it of custom type.

Make your drawRect method in UILabel as

- (void)drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBStrokeColor(context, 207.0f/255.0f, 91.0f/255.0f, 44.0f/255.0f, 1.0f);

    CGContextSetLineWidth(context, 1.0f);

    CGContextMoveToPoint(context, 0, self.bounds.size.height - 1);
    CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height - 1);

    CGContextStrokePath(context);

    [super drawRect:rect]; 

}
fabian789
  • 8,348
  • 4
  • 45
  • 91
saadnib
  • 11,145
  • 2
  • 33
  • 54
2

In Swift 3 the following extension can be used for an underline:

extension UIButton {
    func underlineButton(text: String) {
        let titleString = NSMutableAttributedString(string: text)
        titleString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, text.characters.count))
        self.setAttributedTitle(titleString, for: .normal)
    }
} 
Durga Vundavalli
  • 1,790
  • 22
  • 26
0

To make this a bit simpler (it's a common requirement) I've built a simple UIButton subclass called BVUnderlineButton that you can drop straight into your projects.

It's on Github at https://github.com/benvium/BVUnderlineButton (MIT licence).

You can use it in a XIB / Storyboard or direct via code.

Ben Clayton
  • 80,996
  • 26
  • 120
  • 129