2

I have the below code in my app

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:self.myDisplayTxt];
      [string addAttribute:(NSString*)kCTForegroundColorAttributeName 
                     value:(id)[[UIColor redColor] CGColor]
                     range:NSMakeRange(0,5)];

    self.myTextView.text = string;

When assigning the NSMutableAttributedString to UITextView I get the following error:

Incompatible objective c types struct NSMutableAttributedString expected struct nsstring

So please let me know, how can I display the NSMutableAttributedString in UITextView.

Ondrej Peterka
  • 3,349
  • 4
  • 35
  • 49
user198725878
  • 6,266
  • 18
  • 77
  • 135

3 Answers3

2

You can try to use some library to do that. As omz wrote, the UITextView does not unfortunatelly support the NSAttributedString.

Maybe this one can help you: https://github.com/enormego/EGOTextView

They say about this library the following:

UITextView replacement with additional support for NSAttributedString.

UPDATE: Based on your clarification in the comment for omz's answer, you can look here: Underline text inside uitextview

UPDATE 2: In iOS 6 you can use the NSAttributedString out of the box. For example like this:

UIColor *_red=[UIColor redColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:72.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeColorAttributeName value:_red range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSStrokeWidthAttributeName value:[NSNumber numberWithFloat:-3.0] range:NSMakeRange(0, _stringLength)];
Community
  • 1
  • 1
Ondrej Peterka
  • 3,349
  • 4
  • 35
  • 49
0

You can't, UITextView doesn't support attributed strings. If you really only want to use attributed strings to set the foreground color (as in your example), you could achieve the same by setting the text view's textColor property.

omz
  • 53,243
  • 5
  • 129
  • 141
  • With `UITextView`, no. As @Ondra pointed out, there are a couple of third-party alternatives to `UITextView` that support rich text (attributed strings), but from my experience, they tend to be buggy and incomplete - ymmv. – omz Apr 25 '12 at 12:05
  • 4
    As of iOS 6, `UITextView`s support `NSAttributedStrings`. – Matt Wilding Nov 01 '12 at 19:10
0

You should assign attributed string via UITextView.attributedText property. UITextView.text accepts NSString or plain text only.

textView.attributedText = attributedString;

See documentation:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextView_Class/index.html#//apple_ref/occ/instp/UITextView/attributedText

pronebird
  • 12,068
  • 5
  • 54
  • 82
user3815344
  • 243
  • 1
  • 21