最近小編在項(xiàng)目中遇到了一個(gè)問(wèn)題,就是當(dāng)textField
的textFont
與placeholder
的font
相差較大時(shí),placeholder
的位置竟然偏移了记靡,沒有垂直居中
原來(lái)的代碼
UITextField *textField = [[UITextField alloc]init];
textField.delegate = self;
textField.backgroundColor = [UIColor orangeColor];
textField.font = [UIFont systemFontOfSize:25];
textField.textColor = [UIColor redColor];
textField.textAlignment = NSTextAlignmentLeft;
NSString *text = @"可提現(xiàn)金額300元";
NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:text];
[titleStr addAttributes:@{NSFontAttributeName:kFont(10)} range:NSMakeRange(0, titleStr.length)];
textField.attributedPlaceholder = titleStr;
[self.view addSubview:textField];
原來(lái)的placeholder效果圖.jpg
原來(lái)的text的效果圖.jpg
怎么辦?就這樣的效果ui妹子非要把我祭天不可然磷,沒辦法摄欲,只有趕快弄清楚為什么會(huì)出現(xiàn)這個(gè)問(wèn)題轿亮,然后才能根據(jù)原理去修復(fù)這個(gè)bug。
根據(jù)上網(wǎng)查資料才得知問(wèn)題所在:
placeholder
在UITextField
的位置是以輸入文字光標(biāo)的上端點(diǎn)作為它的顯示位置胸墙,所以當(dāng)我們?cè)O(shè)置的placeholder字體大小與textField設(shè)置的輸入文字大小差別很大時(shí)我注,placeholder的顯示位置就不會(huì)垂直居中而發(fā)生偏移。
解決方法:
小編經(jīng)過(guò)多次嘗試之后發(fā)現(xiàn)都不行迟隅,最后看到了NSMutableParagraphStyle
但骨,我決定使用這個(gè)再試試
// 段落樣式
NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
// minimumLineHeight 最小行高 改變placeholder的最小行高
style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - kFont(10).lineHeight)/2.0;
style.lineSpacing = 10; // 字體的行間距
style.firstLineHeadIndent = 15.f; //首行縮進(jìn)
NSString *text = @"可提現(xiàn)金額300元";
NSMutableAttributedString *titleStr = [[NSMutableAttributedString alloc]initWithString:text];
[titleStr addAttributes:@{NSFontAttributeName:kFont(10), NSParagraphStyleAttributeName:style} range:NSMakeRange(0, titleStr.length)];
textField.attributedPlaceholder = titleStr;
[self.view addSubview:textField];
最后的效果圖:
沒有設(shè)置首行縮進(jìn)
設(shè)置了首行縮進(jìn)
輸入了文字之后
好了,問(wèn)題解決了智袭,怕以后再次遇到奔缠,就記錄一下吧,順便幫那些遇到這個(gè)問(wèn)題的提供個(gè)思路吧~~吼吼