簡體   English   中英

如何清除 UITextView... 真正的

[英]How to clear UITextView… for real

我很慚愧地承認我不知道如何清除UITextView

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

例如,下面的代碼有一個普通的UITextView可以在雙擊時清除( doubleTapAction: )。 加載時,我添加了一個自定義屬性,該屬性也應在清除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;
}

我的自定義屬性還在!

這是錯誤還是預期行為?

這個可怕的黑客可以解決問題:

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

盡管如此,最好確認這是一個錯誤還是預期的行為。 我在文檔中找不到任何關於它的內容。

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

嘗試這個!

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

在我的應用程序中,我看到 hpique 建議的 hack 性能不佳:

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

在這種情況下,有一個屬性很有用。 這是typingAttributes

let textView = UITextView()
let attributes: [NSAttributedString.Key: Any] = [
    .font: UIFont.systemFont(ofSize: 16, weight: .regular),
    .foregroundColor: UIColor.black,
]
textView.typingAttributes = attributes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM