Placeholder in UITextView

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

    It is not possible to create placeholder in UITextView but you can generate effect like place holder by this.

      - (void)viewDidLoad{      
                  commentTxtView.text = @"Comment";
                  commentTxtView.textColor = [UIColor lightGrayColor];
                  commentTxtView.delegate = self;
    
         }
           - (BOOL) textViewShouldBeginEditing:(UITextView *)textView
         {
             commentTxtView.text = @"";
             commentTxtView.textColor = [UIColor blackColor];
             return YES;
         }
    
         -(void) textViewDidChange:(UITextView *)textView
         {
    
        if(commentTxtView.text.length == 0){
            commentTxtView.textColor = [UIColor lightGrayColor];
            commentTxtView.text = @"Comment";
            [commentTxtView resignFirstResponder];
        }
        }
    

    OR you can add label in textview just like

           lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,textView.frame.size.width - 10.0, 34.0)];
    
    
    [lbl setText:kDescriptionPlaceholder];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setTextColor:[UIColor lightGrayColor]];
    textView.delegate = self;
    
    [textView addSubview:lbl];
    

    and set

    - (void)textViewDidEndEditing:(UITextView *)theTextView
    {
         if (![textView hasText]) {
         lbl.hidden = NO;
    }
    }
    
    - (void) textViewDidChange:(UITextView *)textView
    {
        if(![textView hasText]) {
          lbl.hidden = NO;
    }
    else{
        lbl.hidden = YES;
     }  
    }
    

提交回复
热议问题