先直接上成功的代碼径玖,從一個(gè)帖子里查到的。
//當(dāng)將要編輯的時(shí)候颤介,先執(zhí)行這個(gè)代理方法梳星,之后輸入的內(nèi)容也就有了行間距赞赖。
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
// 當(dāng)沒(méi)有字符時(shí)要先臨時(shí)填充一個(gè)字符,再設(shè)置屬性才能有效
if (textView.text.length < 1) {
textView.text = @"間距";
}
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5; // 字體的行間距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:14],
NSParagraphStyleAttributeName:paragraphStyle,
NSKernAttributeName:@1.2f,
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
// 刪除臨時(shí)字符
if ([textView.text isEqualToString:@"間距"]) {
textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];//主要是把“間距”兩個(gè)字給去了冤灾。
}
return YES;
}
注意:無(wú)字符時(shí)要先添加臨時(shí)字符前域,再設(shè)置屬性,否則無(wú)效韵吨。比較奇怪的地方匿垄。
推理發(fā)現(xiàn):
根據(jù)上面的方法,我發(fā)現(xiàn)原來(lái)只要在創(chuàng)建的時(shí)候也在有臨時(shí)字符的情況下賦值屬性归粉,然后刪掉臨時(shí)字符椿疗,也能有相同的效果。
UITextView *textView = [[UITextView alloc] init];
[self.view addSubview:textView];
// textview 改變字體的行間距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;// 字體的行間距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle,
NSKernAttributeName:@1.2f,
};
// 在有臨時(shí)字符的情況下賦值屬性糠悼,不可省略届榄,否則無(wú)效
textView.attributedText = [[NSAttributedString alloc] initWithString:@"間隔" attributes:attributes];
// 刪除臨時(shí)字符
textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];
錯(cuò)誤例子:
可能會(huì)有人直覺(jué)地想到在textViewDidChange里修改,雖有效果但bug嚴(yán)重倔喂。
bug : 輸入中文會(huì)出現(xiàn)字母铝条。每次刪除字符后光標(biāo)都會(huì)回到最后。
- (void)textViewDidChange:(UITextView *)textView {
// textview 改變字體的行間距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;// 字體的行間距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:15],
NSParagraphStyleAttributeName:paragraphStyle,
NSKernAttributeName:@1.2f,
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}