43、[ iOS ] UITextView实现placeHolder占位文字

    // --UITextView
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 100)];
    textView.font = [UIFont systemFontOfSize:17];
    [textView setBackgroundColor:[UIColor cyanColor]];
    [self.view addSubview:textView];
    
    // --_placeholderLabel
    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.font     = [UIFont systemFontOfSize:17];
    placeHolderLabel.text     = @"不能为空";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor lightGrayColor];
    [placeHolderLabel sizeToFit];
    [textView addSubview:placeHolderLabel];
    
    [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    
    注意:必须设置textView和placeHolderLabel的font属性,让他们保持一致。
         不然会出现placeHolderLabel.text第一次显示是向上偏移的,输入内容之后删空才恢复正常这种情况。

你可能感兴趣的:(43、[ iOS ] UITextView实现placeHolder占位文字)