設(shè)置UITextView的行間距有多種方法
一、設(shè)置靜態(tài)textview行間距
UITextView不需要輸入直接顯示非常簡單
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, 100, 200)];
textView.delegate = self;
textView.text = @"大家好大家好大家好大家好這是一個測試text";
[self.view addSubview:textView];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;// 字體的行間距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:17],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
NSMutableParagraphStyle這個類,這是設(shè)置段落風(fēng)格的類,有很多屬性,請自行查看API
二、動態(tài)設(shè)置textview行間距
在textview的代理方法中實現(xiàn)動態(tài)改變行間距
- (void)textViewDidChange:(UITextView *)textView{
UITextRange *selectedRange = [textView markedTextRange];
NSString * newText = [textView textInRange:selectedRange]; //獲取高亮部分
if(newText.length>0)
return;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 4;// 字體的行間距
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:15],NSParagraphStyleAttributeName:paragraphStyle};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
這個方法獲取高亮部分可以避免輸入內(nèi)容不準(zhǔn)確。但是,當(dāng)刪除內(nèi)容時光標(biāo)會一直處于最末位。
三、通過屬性設(shè)置
textView.typingAttributes屬性官方文檔描述是
應(yīng)用于用戶輸入的新文本的屬性。
該字典包含用于新輸入的文本的屬性鍵(以及相應(yīng)的值)。當(dāng)文本視圖的選擇發(fā)生變化時,字典的內(nèi)容自動被清除。
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, 100, 200)];
textView.delegate = self;
[self.view addSubview:textView];
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineSpacing = 20;// 字體的行間距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:17],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.typingAttributes = attributes;
但會有光標(biāo)擴大問題


沒有發(fā)現(xiàn)相關(guān)的屬性來設(shè)置光標(biāo)的顯示, 使用系統(tǒng)的UITextView暫時解決不了上述問題
四、自定義textview
UITextView遵循了UITextInput協(xié)議,其中有返回光標(biāo)frame的方法
- (CGRect)caretRectForPosition:(UITextPosition *)position,所以我們可以使用自定義的TextView,重寫返回光標(biāo)frame的方法避免光標(biāo)擴大問題。
- (CGRect)caretRectForPosition:(UITextPosition *)position {
CGRect originalRect = [super caretRectForPosition:position];
originalRect.size.height = self.font.lineHeight + 2;
originalRect.size.width = 3;
return originalRect;
}