2013-11-26 38 views
17

我在我的UITextview中使用NSMutableParagraphStyle来在每行文本之间添加行距。iOS - UITextView lineSpacing使光标高度不一样

当我在textview中键入内容时,光标高度是正常的。但是当我将光标位置移动到第二行(而不是最后一行)上的文本时,光标高度变得越来越大。

enter image description here

我应该怎么做才能让光标高度文本的每一行中正常吗? 这是我目前使用的代码:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
paragraphStyle.lineSpacing = 30.; 
textView.font = [UIFont fontWithName:@"Helvetica" size:16]; 
textView.attributedText = [[NSAttributedString alloc] initWithString:@"My Text" attributes:@{NSParagraphStyleAttributeName : paragraphStyle}]; 

回答

23

最后我得到解决方案,解决我的问题。

我们可以通过子类UITextView来改变光标高度,然后覆盖caretRectForPosition:position函数。例如:

- (CGRect)caretRectForPosition:(UITextPosition *)position { 
    CGRect originalRect = [super caretRectForPosition:position]; 
    originalRect.size.height = 18.0; 
    return originalRect; 
} 

文档链接:https://developer.apple.com/documentation/uikit/uitextinput/1614518-caretrectforposition

+2

这是一个记录方法? (编辑:是的,它是在'UITextInput'协议'UITextView'符合(https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITextInput_Protocol/index.html#//apple_ref/occ/intf/UITextInput) – oztune

+0

真的很有用,大拇指! – KkMIW

+0

当选择这个文本的句柄真的很大,任何想法如何解决它? –

7

而对于夫特2. X或夫特3. X

import UIKit 

class MyTextView : UITextView { 
    override func caretRectForPosition(position: UITextPosition) -> CGRect { 
     var superRect = super.caretRectForPosition(position) 
     guard let isFont = self.font else { return superRect } 

     superRect.size.height = isFont.pointSize - isFont.descender 
      // "descender" is expressed as a negative value, 
      // so to add its height you must subtract its value 

     return superRect 
    } 
}