Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear UITextView... for real

I'm ashamed to admit that I don't know how to clear a UITextView.

By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to nil would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added.

For example, the following code has a vanilla UITextView that can be cleared on double tap (doubleTapAction:). When loaded, I add a custom attribute that should also be removed when the UITextView is cleared.

@implementation HPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"];
    [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)];
    self.textView.attributedText = attributedString;
}

- (IBAction)doubleTapAction:(id)sender
{
    self.textView.text = nil;
    // Also tried:
    // self.textView.text = @"";
    // self.textView.attributedText = nil;
    // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""];
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSLog(@"%@", textView.attributedText);
}

@end

Clearing the UITextView and then typing the letter "d" logs the following:

d{
    NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n    28L,\n    56L,\n    84L,\n    112L,\n    140L,\n    168L,\n    196L,\n    224L,\n    252L,\n    280L,\n    308L,\n    336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
    attribute = value;
}

My custom attribute is still there!

Is this a bug or expected behaviour?

like image 681
hpique Avatar asked Feb 12 '14 14:02

hpique


3 Answers

This awful hack does the trick:

self.textView.text = @"Something, doesn't matter what as long as it's not empty";
self.textView.text = @"";

Still, it would be nice to confirm if this is a bug or expected behaviour. I couldn't find anything in the documentation about it.

like image 196
hpique Avatar answered Sep 28 '22 08:09

hpique


textView.text=@"";
[textView insertText:@""];

try this!

like image 22
user3044484 Avatar answered Sep 28 '22 06:09

user3044484


You have to manually reset font, text color etc. to your default values. Setting attributedText always sets the UITextView's "global" attributes to those of the first letter in the attributed string.

like image 30
johnyu Avatar answered Sep 28 '22 08:09

johnyu