文本框的占位文字属性设置的4种方法

- (void)awakeFromNib
{
    // 设置输入时文字的颜色
    self.textColor = [UIColor whiteColor];

    // 设置鼠标光标的颜色
    self.tintColor = [UIColor whiteColor];

    // 设置带属性的占位文字的颜色
    // 方法1
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName : [UIColor grayColor]}];
    // 或
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];

    // 方法2
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self.placeholder];
    [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, self.placeholder.length)];
    self.attributedPlaceholder  =attrStr;

    // 富文本的扩展,可实现图文混排
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] init];

    // 第一段文字
    NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:self.placeholder];
    [attrString appendAttributedString:str1];

    // 第二段图片
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"nav_coin_icon_click"];
    NSAttributedString *str2 = [NSAttributedString attributedStringWithAttachment:attachment];
    [attrString appendAttributedString:str2];

    // 第三段文字
    NSAttributedString *str3 = [[NSAttributedString alloc] initWithString:@"您好"];
    [attrString appendAttributedString:str3];

    self.attributedPlaceholder = attrString;

     // 方法3,调用drawPlaceholderInRect:方法实现

    // 方法4,利用运行时的实现原理,获取输入框中占位符的属性名,从而给其赋值
    UILabel *label = [self valueForKeyPath:@"placeholderLabel"];
    label.textColor = [UIColor grayColor];
    // 或
    [self setValue:[UIColor grayColor] forKeyPath:@"placeholderLabel.textColor"];
}

/**
 *  方法3,调用drawPlaceholderInRect:方法实现
 */
- (void)drawPlaceholderInRect:(CGRect)rect
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    attrs[NSFontAttributeName] = self.font;

    // 方式一
    CGRect bounds = self.bounds;
    bounds.origin.y = (self.height - self.font.lineHeight) * 0.5;

    [self.placeholder drawInRect:bounds withAttributes:attrs];

    // 方式二
    CGPoint point;
    point.x = 0;
    point.y = (self.height - self.font.lineHeight) * 0.5;

    [self.placeholder drawAtPoint:point withAttributes:attrs];
}

你可能感兴趣的:(iOS那些事)