简体   繁体   English

单击 TextView 时删除属性文本

[英]Delete Attributed Text When You Click on TextView

I'm having trouble figuring out how to delete attributed text when a user clicks on a textView , much like it does when you do on a textField .当用户单击textView ,我无法弄清楚如何删除属性文本,就像您在textField上所做的那样。 I know how to assign the attributed text, but I want it to disappear when a user clicks on the textView , rather than having to delete the attributed text themselves.我知道如何分配属性文本,但我希望它在用户单击textView时消失,而不必自己删除属性文本。

Here is the code I'm using to populate:这是我用来填充的代码:

 if([self.detailItem.comments.rootBeerComment isEqual: @""] || self.detailItem.comments.rootBeerComment == nil){
            NSAttributedString *string = [[NSAttributedString alloc]initWithString:@"Notes..."];
            self.rootBeerNotes.attributedText = string;
        }else{
            self.rootBeerNotes.text = self.detailItem.comments.rootBeerComment; 
        }

In order to do something when the textView is tapped, you need to know when this event happens.为了在 textView 被点击时做一些事情,你需要知道这个事件何时发生。 The easiest way is to set the delegate of the textView to your view controller, and then implement the UITextViewDelegate delegate method which tells you this:最简单的方法是将 textView 的委托设置为您的视图控制器,然后实现UITextViewDelegate委托方法,它告诉您:

- (BOOL)textViewShouldBeginEditing:(UITextField *)textView
{
    // You may need to check that it is the right textView if you have more than one.
    textView.attributedText = nil;
    return YES;
}

As an aside, you can replace this line of code:顺便说一句,您可以替换这行代码:

if([self.detailItem.comments.rootBeerComment isEqual: @""] || self.detailItem.comments.rootBeerComment == nil){

with this one, which is shorter and does the same thing since the length of an empty string and the length of a nil object will both return 0:有了这个,它更短并且做同样的事情,因为空字符串的长度和 nil 对象的长度都将返回 0:

if([self.detailItem.comments.rootBeerComment length] == 0){

You can always use this.您可以随时使用它。 Make an NSRange that is from the first to the last character and use an empty string "".创建一个从第一个字符到最后一个字符的 NSRange,并使用一个空字符串“”。

myAttributedString.replaceCharacters(in range: NSRange, with str: String) myAttributedString.replaceCharacters(范围内:NSRange,与str:字符串)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM