iOS之UITextField实现图文混排的placeHolder

前言:项目中遇见的一个小需求,觉着挺有意思的,这里记录一下。
1.需求:想要实现的效果如图所示,即在TextField中居中展示一个搜索图标+一段默认文字。
2.实现思路:当然实现的思路有多种,这里我主要是利用UITextField的属性attributedPlaceholder,实现一个图文混排的NSMutableAttributedString.
iOS之UITextField实现图文混排的placeHolder_第1张图片
效果图.png
3.实现中遇到的问题:

a.图文混排内容在Textfield中居中的问题

问题a.png

b.图文混排的图片与文字不对齐的问题

问题b.png

废话不多说,直接上我主要实现代码:

    self.view.backgroundColor = [UIColor lightGrayColor];
    
    self.searchTextfield = [[UITextField alloc]initWithFrame:CGRectMake(20, 40, [[UIScreen mainScreen] bounds].size.width-40, 40)];
    self.searchTextfield.backgroundColor = [UIColor whiteColor];
    self.searchTextfield.borderStyle = UITextBorderStyleRoundedRect;
    NSString *textString = @"请输入用户手机号搜索";
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:textString];
    // 插入图片附件
    NSTextAttachment *imageAtta = [[NSTextAttachment alloc] init];
    imageAtta.bounds = CGRectMake(0, 0, 21, 21);
    imageAtta.image = [UIImage imageNamed:@"f_search"];
    NSAttributedString *attach = [NSAttributedString attributedStringWithAttachment:imageAtta];
    [attributeString insertAttributedString:attach atIndex:0];
    
    // 段落样式
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    ///计算placeHolder文字宽度
    CGSize textSize = [textString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size;
    
    // 缩进以实现居中展示(解决问题a)
    [style setFirstLineHeadIndent:([[UIScreen mainScreen] bounds].size.width-40-21-textSize.width)/2.0];
    [attributeString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, attributeString.length)];
    
    [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(1, attributeString.length - 1)];
    ///解决问题b
    [attributeString addAttribute:NSBaselineOffsetAttributeName value:@(0.36 * 16) range:NSMakeRange(1, attributeString.length - 1)];
    self.searchTextfield.attributedPlaceholder = attributeString;
    [self.view addSubview:self.searchTextfield];

问题b解决借鉴自 解决使用NSMutableAttributedString 设置不同字体,文字不能居中对齐
最终实现效果:

iOS之UITextField实现图文混排的placeHolder_第2张图片
finalResult.gif

你可能感兴趣的:(iOS之UITextField实现图文混排的placeHolder)