Placeholder in UITextView

前端 未结 30 2829
野趣味
野趣味 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:02

    Here's a way easier solution that behaves exactly like UITextField's placeholder but doesn't require drawing custom views, or resigning first responder.

    - (void) textViewDidChange:(UITextView *)textView{
    
        if (textView.text.length == 0){
            textView.textColor = [UIColor lightGrayColor];
            textView.text = placeholderText;
            [textView setSelectedRange:NSMakeRange(0, 0)];
            isPlaceholder = YES;
    
        } else if (isPlaceholder && ![textView.text isEqualToString:placeholderText]) {
            textView.text = [textView.text substringToIndex:1];
            textView.textColor = [UIColor blackColor];
            isPlaceholder = NO;
        }
    
    }
    

    (the second check in the else if statement is for the case where nothing is entered and the user presses backspace)

    Just set your class as a UITextViewDelegate. In viewDidLoad you should initialize like

    - (void) viewDidLoad{
        // initialize placeholder text
        placeholderText = @"some placeholder";
        isPlaceholder = YES;
        self.someTextView.text = placeholderText;
        self.someTextView.textColor = [UIColor lightGrayColor];
        [self.someTextView setSelectedRange:NSMakeRange(0, 0)];
    
        // assign UITextViewDelegate
        self.someTextView.delegate = self;
    }
    

提交回复
热议问题