Placeholder in UITextView

前端 未结 30 3077
野趣味
野趣味 2020-11-22 16:01

My application uses an UITextView. Now I want the UITextView to have a placeholder similar to the one you can set for an UITextField.<

30条回答
  •  渐次进展
    2020-11-22 16:19

    I extended KmKndy's answer, so that the placeholder remains visible until the user starts editing the UITextView rather than just taps on it. This mirrors the functionality in the Twitter and Facebook apps. My solution doesn't require you to subclass and works if the user types directly or pastes text!

    Example of Placeholder Twitter App

    - (void)textViewDidChangeSelection:(UITextView *)textView{
        if ([textView.text isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]])[textView setSelectedRange:NSMakeRange(0, 0)];
    
    }
    
    - (void)textViewDidBeginEditing:(UITextView *)textView{
    
        [textView setSelectedRange:NSMakeRange(0, 0)];
    }
    
    - (void)textViewDidChange:(UITextView *)textView
    {
        if (textView.text.length != 0 && [[textView.text substringFromIndex:1] isEqualToString:@"What's happening?"] && [textView.textColor isEqual:[UIColor lightGrayColor]]){
            textView.text = [textView.text substringToIndex:1];
            textView.textColor = [UIColor blackColor]; //optional
    
        }
        else if(textView.text.length == 0){
            textView.text = @"What's happening?";
            textView.textColor = [UIColor lightGrayColor];
            [textView setSelectedRange:NSMakeRange(0, 0)];
        }
    }
    
    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        if ([textView.text isEqualToString:@""]) {
            textView.text = @"What's happening?";
            textView.textColor = [UIColor lightGrayColor]; //optional
        }
        [textView resignFirstResponder];
    }
    
    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
        if (textView.text.length > 1 && [textView.text isEqualToString:@"What's happening?"]) {
             textView.text = @"";
             textView.textColor = [UIColor blackColor];
        }
    
        return YES;
    }
    

    just remember to set myUITextView with the exact text on creation e.g.

    UITextView *myUITextView = [[UITextView alloc] init];
    myUITextView.delegate = self;
    myUITextView.text = @"What's happening?";
    myUITextView.textColor = [UIColor lightGrayColor]; //optional
    

    and make the parent class a UITextView delegate before including these methods e.g.

    @interface MyClass () 
    @end
    

提交回复
热议问题