简体   繁体   中英

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 . 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.

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. 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:

- (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:

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 "".

myAttributedString.replaceCharacters(in range: NSRange, with str: String)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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