UITextView 的placeholder

UITextField是没有分行功能,如果先要输入多行文字,就需要用到UITextView,但是在使用UITextView的时候,我们也想给用户一个提示语,这个怎么实现呢??

说起UITextfield的placeholder,大家都不陌生,因为在UITextfield中有这个属性,之久给这个属性赋值,就可以实现提示的作用,但是在UITextView中你是否用过呢?, 在这里我告诉你UITextView是没有自带的placeholder这个属性的。如果想要实现这个功能就需要自己来实现。要如何实现呢?

下面是我实现的代码:

#import <UIKit/UIKit.h>

@interface MyTextViewPlaceholder : UITextView

@property (nonatomic, strong) NSString *placeholder;
@property (nonatomic, strong) UIColor *placeholderColor;

@end

============================================

#import "MyTextViewPlaceholder.h"

@implementation MyTextViewPlaceholder


/**
 * 重写init方法  同时初始化一个通知,用来检测textView内容的改变
 */

- (instancetype)init
{
    self = [super init];
    if (self) {

        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setNeedsDisplay) name:UITextViewTextDidChangeNotification object:nil];

        self.placeholder = @"";
        self.placeholderColor = [UIColor redColor];


    }
    return self;
}

//绘制 placeholder的位置
-(void)drawRect:(CGRect)rect {

    //    if ([self.text isEqualToString:@""]) {
    if (!self.hasText) {

        CGRect placeholderRect;

        //设置placeholder的位置
        placeholderRect.origin.y = 8;
        placeholderRect.size.height = CGRectGetHeight(self.frame) - 8;

        placeholderRect.origin.x = 10;
        placeholderRect.size.width = CGRectGetWidth(self.frame) - 10;

        [self.placeholderColor set];

        //绘制placeholder
        [self.placeholder drawInRect:placeholderRect withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName: _placeholderColor}];
    }
}

//如果设置了为本内容  就重新绘制placeholder的内容
- (void)setText:(NSString *)text {
    [super setText:text];
    [self setNeedsDisplay];
}

@end

使用的时候直接初始化就可以了,然后直接设置placeholder的内容已经placeholder的颜色。 代码如下:

  myPlaceholder = [MyTextViewPlaceholder new];
    myPlaceholder.frame = CGRectMake(10, 100, self.view.frame.size.width - 40, 100);
    //我在MyTextViewPlaceholder 中重写的时init方法,所以初始化的时候不能调用下面的方法
//    MyTextViewPlaceholder * myPlaceholder =[[MyTextViewPlaceholder alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width - 40, 100)];

    myPlaceholder.placeholder = @"12341234123412341234123412341234123412341234123412341234";
    myPlaceholder.placeholderColor = [UIColor orangeColor];
    myPlaceholder.delegate = self;
//    myPlaceholder.text = @"改变后的";
    [self.view addSubview:myPlaceholder];

到这里就完成了,这样就实现了UITextview 和UITextfield的placeholder一样的占位符功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值