iOS 设置带占位文字的TextView

原生TextView无占位文字, 可通过drawRect:方法为其添加占位文字, 具体设置如下:

1. 获取当前占位文字属性:

// 文字属性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font; // 获取当前PlaceholderTextView的文字属性
attrs[NSForegroundColorAttributeName] = self.placeholderColor ? self.placeholderColor : [UIColor lightGrayColor];

 

2. 设置绘制范围(包含文字边距):

// 绘制范围
CGFloat placeholderTopMargin = self.placeholderTopMargin ? self.placeholderTopMargin : kPlaceholderDefaultTopMargin;
CGFloat placeholderLeftMargin = self.placeholderLeftMargin ? self.placeholderLeftMargin : kPlaceholderDefaultTopMargin;
    
CGFloat placeholderX = placeholderTopMargin;
CGFloat placeholderY = placeholderLeftMargin;
CGFloat placeholderW = rect.size.width - 2 * placeholderLeftMargin;
CGFloat placeholderH = rect.size.height - 2 * placeholderTopMargin;
CGRect placeholderRect = CGRectMake(placeholderX, placeholderY, placeholderW, placeholderH);
    
[self.placeholder drawInRect:placeholderRect withAttributes:attrs];

 

3. 通过通知或代理, 当TextView文字发生改变时, 重新绘制:

// 设置通知, 当TextView文字发生改变时, 向自己发送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChanged) name:UITextViewTextDidChangeNotification object:self];

通知事件:

- (void)textDidChanged
{
    // 重新绘制
    [self setNeedsDisplay];
}

 

4. 重写TextView属性方法, 实时绘制:

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    
    // 会在下一个消息循环调用drawRect
    [self setNeedsDisplay];
}

 

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    _placeholderColor = placeholderColor;
    
    [self setNeedsDisplay];
}

 

- (void)setText:(NSString *)text
{
    [super setText:text]; // 系统自带属性
    
    [self setNeedsDisplay];
}

 

- (void)setAttributedText:(NSAttributedString *)attributedText
{
    [super setAttributedText:attributedText];
    
    [self setNeedsDisplay];
}

 

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    
    [self setNeedsDisplay];
}

 

GitHubs:https://github.com/BigPlane/CHPlaceholderTextView

转载于:https://www.cnblogs.com/happyplane/p/4775345.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值