前言:項目中遇見的一個小需求,覺著挺有意思的榛鼎,這里記錄一下乞封。
1.需求:想要實(shí)現(xiàn)的效果如圖所示,即在TextField中居中展示一個搜索圖標(biāo)+一段默認(rèn)文字蜈首。
2.實(shí)現(xiàn)思路:當(dāng)然實(shí)現(xiàn)的思路有多種嗅蔬,這里我主要是利用UITextField的屬性attributedPlaceholder,實(shí)現(xiàn)一個圖文混排的NSMutableAttributedString.
效果圖.png
3.實(shí)現(xiàn)中遇到的問題:
a.圖文混排內(nèi)容在Textfield中居中的問題
問題a.png
b.圖文混排的圖片與文字不對齊的問題
問題b.png
廢話不多說疾就,直接上我主要實(shí)現(xiàn)代碼:
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 = @"請輸入用戶手機(jī)號搜索";
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;
// 縮進(jìn)以實(shí)現(xiàn)居中展示(解決問題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 設(shè)置不同字體澜术,文字不能居中對齊
最終實(shí)現(xiàn)效果:
finalResult.gif