iOS学习笔记iOSiOS开发记录

重写textField的占位符

2016-03-25  本文已影响377人  蒋昉霖

有的时候产品给的需求里面,占位符的颜色大小什么的是有规定的,这个时候我们怎么办呢...

一般的设置占位字符串的代码如下

    self.tf.placeholder = @"hello";
//    self.tf.placeholder.backgroundColor = [UIColor redColor];

这个第二句是直接报错的,不能更改

那么我们点开占位符的属性列表,发现是没有办法更改颜色,底色,大小等属性的

怎么办呢
下面提供三种常用的方法来解决这个问题

带属性的占位符

跟带属性的字符串一样,有一个带属性的占位符,替换掉就好了,代码如下

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSBackgroundColorAttributeName] = [UIColor redColor];
    
    NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"hello" attributes:dict];
    self.tf.attributedPlaceholder = string;

这个方法只能让所有的占位符达到一个效果,只是有简单功能
这个可变字符串的Key值就不一一介绍了,敷个链接上来

可变的带属性的字符串

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSBackgroundColorAttributeName] = [UIColor redColor];
    
    NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"hello" attributes:dict];
    self.tf.attributedPlaceholder = string;

这个还是相对比较好用的,可以根据Rang实现字符串不同区域不同样式

重写textFiled

我们可以自定义一个自己的tf,然后在xib或者纯代码里面,创建自己写的tf,然后在tf内部进行重构就可以了
这个方法最为彻底,基本满足你任何需求

// 在tf里重写这个方法就可以了
- (void)drawPlaceholderInRect:(CGRect)rect
{
    [self.placeholder drawInRect:CGRectMake(0, 10, rect.size.width, 0) withAttributes:@{
                                                       NSForegroundColorAttributeName : [UIColor redColor],
                                                       NSFontAttributeName : self.font}];
}

还有别的方法,比如自己画一个占位符,比如放一个label上去,在点击的时候label隐藏,当然都比较非主流了,好了,就这些,回家吃饭

上一篇 下一篇

猜你喜欢

热点阅读