UITextView占位文字(placeHolder)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UITextView占位文字(placeHolder)相关的知识,希望对你有一定的参考价值。

- (void)viewDidLoad {

    [super viewDidLoad];

 

    self.contentTV = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, APPSCREEN_WIDTH - 40, 100)];

    self.contentTV.layer.borderWidth = 0.5;

    self.contentTV.delegate = self;

    self.contentTV.attributedText = [self stringTurnToAttstrWithString:@"   *我要留言:"];

    self.contentTV.font = [UIFont systemFontOfSize:15];

    self.contentTV.layer.borderColor = [UIColor lightGrayColor].CGColor;

    [self.view addSubview:self.contentTV];

}

 

- (NSMutableAttributedString *)stringTurnToAttstrWithString:(NSString *)string{

    

    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString:string];

    //颜色

    [attStr addAttribute:NSForegroundColorAttributeName

                   value:[UIColor redColor]

                   range:NSMakeRange(3, 1)];

    [attStr addAttribute:NSForegroundColorAttributeName

                   value:RGBCOLORV(0xaaaaaa)

                   range:NSMakeRange(4, string.length - 4)];

    //字体大小

    [attStr addAttribute:NSFontAttributeName

                   value:[UIFont systemFontOfSize:15]

                   range:NSMakeRange(0, attStr.length)];

    return attStr;

}

 

- (void)textViewDidBeginEditing:(UITextView *)textView{

    

    if ([textView.text isEqualToString:@"   *我要留言:"]) {

        

        textView.attributedText = [[NSMutableAttributedString alloc] initWithString:@""];

    }

    textView.textColor = RGBCOLORV(0x000000);

    

}

 

- (void)textViewDidEndEditing:(UITextView *)textView{

    

    if (textView.attributedText.length == 0) {

        

        textView.attributedText = [self stringTurnToAttstrWithString:@"   *我要留言:"];

    }

}

 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    

    UITouch *tc = [touches anyObject];

    if ([self.contentTV isFirstResponder] && tc.view != self.contentTV) {

        

        [self.contentTV resignFirstResponder];

    }

}

 

以上是关于UITextView占位文字(placeHolder)的主要内容,如果未能解决你的问题,请参考以下文章

iOS中用UILabel实现UITextView的占位文字

Objective-C自定义UITextView(placeholder,长按换行,文字位置文字间距等)

如何在 UITextView 中插入占位符? [复制]

iOS 给UITextView加一个placeholder

为HTML5 Placeholder占位文字添加CSS样式

UITextView默认文字