繁体   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