11

How can I underline text in a UITextView. I understand that I would need to create a subclass of UITextView, but what would go under drawRect:?

Thanks.

James Anderson
  • 556
  • 3
  • 16
  • 41

14 Answers14

23

Try to use NSAttributedString as follows and set in UITextView. This works for iOS6.

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"Some String"];
[attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName 
                   value:[NSNumber numberWithInt:kCTUnderlineStyleSingle] 
                   range:(NSRange){0,[attString length]}];

For more info on NSAttributedString check this How do you use NSAttributedString?

For eg:-

textView.attributedText = attString;

From apple documentation on UITextView,

In iOS 6 and later, this class supports multiple text styles through use of the attributedText property. (Styled text is not supported in earlier versions of iOS.) Setting a value for this property causes the text view to use the style information provided in the attributed string. You can still use the font, textColor, and textAlignment properties to set style attributes, but those properties apply to all of the text in the text view.

attributedText:

The styled text displayed by the text view.

@property(nonatomic,copy) NSAttributedString *attributedText

Discussion: This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and textAlignment properties so that they reflect the style information starting at location 0 in the attributed string.

Community
  • 1
  • 1
iDev
  • 23,310
  • 7
  • 60
  • 85
  • Hi, when you say 'set in UITextView', how do you mean? Could you post an example of how to do this? – James Anderson Oct 29 '12 at 08:35
  • @d3v3l0p3r101, Updated my answer. Check it. – iDev Oct 29 '12 at 08:42
  • Thanks - really appreciated! I'm getting this error with the NSAttributedString code though: http://pixelbit.in/KV2u. – James Anderson Oct 29 '12 at 08:46
  • I added the coretext framework, the same issue still occurs :( – James Anderson Oct 29 '12 at 09:09
  • I found the issue - it had to be an NSMutableAttributedString – James Anderson Oct 29 '12 at 09:23
  • Oops! I missed that. Even I was thinking why that error came for you where as I can see that it is available in the class. I will update my answer. Thanks! – iDev Oct 29 '12 at 09:27
  • Just one last question - is there any way I can undo this underlining in the UITextView? Like textView.attributedText = nil? Except that also removes all the text... – James Anderson Oct 29 '12 at 09:58
  • You can use - (void)removeAttribute:(NSString *)name range:(NSRange)aRange similar to the above addAttribute method and set it on textView.attributedText = attString; again. Rest of the code will remain same except for addAttribute change to removeAttribute. If this answer is helpful, can you please accept it. :) – iDev Oct 29 '12 at 18:10
  • Any alternative option for iOS 5.0 ? – Solid Soft Apr 12 '13 at 07:15
  • This can actually be written a bit more concisely: `self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:@{ NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle) }];` – Tim Arnold Mar 18 '14 at 14:25
8

If you want to avoid having to include CoreText, you can utilize an attributed string with this attribute:

@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}
Ray Fix
  • 5,575
  • 3
  • 28
  • 30
8

If this is static text, you can underline it in Interface Builder. Make sure to make the text 'Attributed' first by selecting 'Attributed' in the drop down menu:

enter image description here

Adam Johns
  • 35,397
  • 25
  • 123
  • 176
  • and open fonts through the context menu: select the text, then right-click and choose fonts from the menu. – Arjan Oct 05 '19 at 09:09
2
textViewMessage.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle]};
Chris Loonam
  • 5,735
  • 6
  • 41
  • 63
jose920405
  • 7,982
  • 6
  • 45
  • 71
1

If you want to format your text (with underlined words, links, colored words...) I suggest you to use FTCoreText

Solidus
  • 251
  • 2
  • 10
1
-(IBAction)underline:(id)sender
{
    NSDictionary *underlineAttribute = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    texts.attributedText = [[NSAttributedString alloc] initWithString:texts.text
                                                           attributes:underlineAttribute];
}
Mihriban Minaz
  • 3,043
  • 2
  • 32
  • 52
1

You can't use "kCTUnderlineStyleAttributeName" or "kCTUnderlineStyleSingle" Now you must do it like this:

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"Text"];
[attString addAttribute:NSUnderlineStyleAttributeName
                  value:@(NSUnderlineStyleSingle)
                  range:(NSRange){0,[attString length]}];
Tayo119
  • 331
  • 4
  • 11
0

If you are using iOS 6 then you can use the attributedText attribute of UITextView. Apply underline formatting to the text. You can also set the typingAttributes property to ensure the text that the user types has a specific set of formatting if you wish.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

I recommend you to use CoreText. A Basic tutorial is here on raywenderlich.

Mathew Varghese
  • 4,527
  • 2
  • 17
  • 26
0

I recommend you to use MFUnderlinedTextView, it will be helpful.

yebw
  • 247
  • 1
  • 3
  • 11
0

This is how I did it using Swift 5:

let attributedString = NSMutableAttributedString(string: myTextView.text ?? "")
myTextView.linkTextAttributes = [NSAttributedString.Key(rawValue: NSAttributedString.Key.underlineStyle.rawValue): NSUnderlineStyle.single.rawValue] as [NSAttributedString.Key: Any]?
myTextView.attributedText = attributedString
jaytrixz
  • 4,059
  • 7
  • 38
  • 57
0

Swift 5. As my UITextView if for inserting text, I created an extension function as bellow.

extension UITextView {

  func underlined() {
    let border = CALayer()
    let width = CGFloat(1.0)
    border.borderColor = UIColor.lightGray.cgColor
    border.frame = CGRect(x: 0, y: self.frame.size.height - 5, width:  self.frame.size.width, height: 1)
    border.borderWidth = width
    self.layer.addSublayer(border)
    self.layer.masksToBounds = true
    let style = NSMutableParagraphStyle()
    style.lineSpacing = 15
    let attributes = [NSAttributedString.Key.paragraphStyle : style, NSAttributedString.Key.foregroundColor : UIColor.darkGray, NSAttributedString.Key.font :  UIFont.systemFont(ofSize: 13)]
    self.attributedText = NSAttributedString(string: self.text, attributes: attributes)
  }

}

The border is drawling the line and the style is adding the spacing between the lines. Usage in your UIView custom layout:

override func layoutSubviews() {
    super.layoutSubviews()
    self.dateAndTimeInput.underlined()
  }

Image with the result

0
       let someString = NSMutableAttributedString(string: "Your String", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue])
        someStringTextView.attributedText = titleAT
       

U can just give your string a bunch of attributes like bold, underlined etc.

-3

To underline a text, you have to go where you can select copy, cut , delete options there are now more options like B/I/U( bold, italic, underline). Choose this option and this is it. And to unable it, choose underline option again.