2014-02-12 67 views
5

我很慚愧承認我不知道如何清除UITextView如何清除UITextView ...爲真

通過清除,我的意思是留下它的文本空白,並刪除其所有屬性。我認爲將它設置爲nil就足夠了,但第一個字符的屬性仍然存在,靜靜地等待,直到我再次輸入。

例如,以下代碼具有可在雙擊(doubleTapAction:)上清除的香草UITextView。加載時,我添加了一個自定義屬性,該屬性在UITextView被清除時也應該被刪除。

@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 

清除UITextView,然後鍵入字母 「d」 記錄以下:

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

我的自定義屬性仍然存在!

這是一個錯誤或預期的行爲?

回答

6

這可怕的黑客的伎倆:

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

不過,這將是很好,確認這是否是一個錯誤或預期的行爲。我在文檔中找不到任何內容。

+1

這是我(不情願)也這樣做的方式。 – JMarsh

1

您必須手動將字體,文本顏色等重置爲默認值。設置屬性字體總是將UITextView的「全局」屬性設置爲屬性字符串中第一個字母的屬性。

+0

但願重置自定義屬性?編輯:不,不。我詢問所有的屬性,不僅僅是段落,顏色和字體。 – hpique

+0

只需添加self.textView.textColor = <您的默認顏色>,以及類似於NSAttributedString可能更改的每個屬性的內容。 – johnyu

+0

UITextView只顯示少數屬性。這不夠。 – hpique

1

在我的應用程序,我從hpique建議的黑客看到表現不佳:

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

第一行強制UITextView的重新佈局的一切。如果UITextView被用在重用的單元格中(例如在UITableView中),這是非常昂貴的。

在iOS系統中8,後來我發現它更與我的UITextView子類下面的復位方法高性能:

- (void)reset 
{  
    self.text = nil; 
    self.font = nil; 
    self.textColor = nil; 
    self.textAlignment = NSTextAlignmentLeft; 
}