Placeholder in UITextView

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

    You could also create a new class TextViewWithPlaceholder as a subclass of UITextView.

    (This code is kind of rough -- but I think it's on the right track.)

    @interface TextViewWithPlaceholder : UITextView
    {
    
        NSString *placeholderText;  // make a property
        UIColor *placeholderColor;  // make a property
        UIColor *normalTextColor;   // cache text color here whenever you switch to the placeholderColor
    }
    
    - (void) setTextColor: (UIColor*) color
    {
       normalTextColor = color;
       [super setTextColor: color];
    }
    
    - (void) updateForTextChange
    {
        if ([self.text length] == 0)
        { 
            normalTextColor = self.textColor;
            self.textColor = placeholderColor;
            self.text = placeholderText;
        }
        else
        {
            self.textColor = normalTextColor;
        }
    
    }
    

    In your delegate, add this:

    - (void)textViewDidChange:(UITextView *)textView
    {
        if ([textView respondsToSelector: @selector(updateForTextChange)])
        {
            [textView updateForTextChange];
        }
    
    }
    

提交回复
热议问题