Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Underline the Button Text of UIButton?

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?

like image 795
Devang Avatar asked Mar 26 '11 12:03

Devang


People also ask

How do you underline text in Uibutton?

Highlight the text in the Attributes inspector. Right click, choose Font and then Underline.

How do you underline a button with text in CSS?

The property text-decoration-line is used to underline the text. This property has three values that are overline, underline, or line-through. So, the value underline is used to underline the text in CSS. This value draws the underline beneath the inline text.

Which button is clicked to underline a text?

The quickest way to underline text is to press Ctrl+U and start typing. When you want to stop underlining, press Ctrl+U again. You can also underline text and spaces in several other ways.


3 Answers

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];
like image 118
HDdeveloper Avatar answered Oct 30 '22 13:10

HDdeveloper


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

}
like image 39
saadnib Avatar answered Oct 30 '22 13:10

saadnib


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)
    }
} 
like image 33
Durga Vundavalli Avatar answered Oct 30 '22 14:10

Durga Vundavalli