iOS关于UITextView自定义PlaceHolder

  • 开发过程中有收获会使用到输入框,但是UITextField又不可以换行,使用UITextView虽然可以换行,但是却没有PlaceHolder,下面介绍如何使用,UITextView中添加一个label默认位是PlaceHolder
    #import "ViewController.h"
    @interface ViewController ()
    @property(nonatomic,strong)UILabel *label;
    @end
  • 在viewDidload方法中创建textview和label
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, 300, 100)];
    textView.delegate = self;
    textView.layer.borderColor =[UIColor redColor].CGColor;
    textView.layer.borderWidth = 1.0;
    _label = [[UILabel alloc] initWithFrame:CGRectMake(55, 102, 100, 20)];
    _label.text = @"请输入东西";
    [self.view addSubview:textView];
    [self.view addSubview:self.label];
  • 然后再UITextView的delegate里边做相应地逻辑处理
    - (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
    _label.text = @" ";
    }else{
    _label.text = @"";
    }
    return YES;
    }
    -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    {
    if ([text isEqualToString:@"\n"]) {
    if ([textView.text isEqualToString:@""] ||textView.text== nil) {
    _label.text = @"请输入东西";
    }
    [textView resignFirstResponder];
    return NO;
    }
    return YES;
    }

你可能感兴趣的:(iOS关于UITextView自定义PlaceHolder)