ios - 如何在UITextView中获取当前选择的行号?

标签 ios uitextview uitextinput uitextposition

I am using the below written method for getting the current selected line number of textView having attributed text. It works fine if last line is not blank. If last line goes blank this method is not giving a proper line number. 

Method : 

    - (NSInteger)getCurrentLineIndex{
        /*
         Get Current Line Inside UITextView
         */
        CGPoint cursorPosition = [self caretRectForPosition:self.selectedTextRange.start].origin;
        return (NSInteger)(cursorPosition.y / self.font.lineHeight);
    }

Is there any other way to get the current line index?


Fixed :  I already had mRangesArray in which each object gave a range of each line. Using those range objects and comparing with the selected range, I was able to fix the problem.

1)获取范围数组
-(无效)分析
{
如果(self.mRangesArray!= nil){
[self.mRangesArray removeAllObjects];
}
NSString * string = self.text;
NSUInteger numberOfLines,索引,stringLength = [字符串长度];
    NSMutableArray *ranges = [NSMutableArray new];
    for (index = 0, numberOfLines = 0; index < stringLength; numberOfLines++)
    {
        NSRange range = [string lineRangeForRange:NSMakeRange(index, 0)];
        [ranges addObject:[NSValue valueWithRange:range]];
    }
    if (self.mRangesArray == nil) {
        self.mRangesArray = [[NSMutableArray alloc]init];
    }
    self.mRangesArray = ranges;
}

2)比较RangesArray中的Range对象与当前选定的Range
-(NSInteger)getCurrentLineIndex {
/ *
此方法将用于获取mRangesArray
* /
[自我分析];
    /*
     Get Current Line Inside UITextView
     */

    NSRange selectedRange = self.selectedRange;

   __block NSInteger index = [self.mRangesArray count]-1;
    [self.mRangesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSRange objectRange = [obj rangeValue];
        if (*stop == NO) {
            if (NSLocationInRange(selectedRange.location, objectRange)) {
                index = idx;
                *stop =YES;
                return;
              }
        }
    }];

}

谢谢大家帮助。干杯:)

最佳答案

编辑:我显然已经忽略了您问题中当前选中的部分的
如果有人需要,我仍将代码保留在这里。

您是否尝试过计算换行符?

let str = "First\nSecond\nThird"
let tok = str.componentsSeparatedByString("\n")
print(tok.count) // Hopefully prints "3"

关于ios - 如何在UITextView中获取当前选择的行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391593/

相关文章:

ios - CustomTextField - 自动完成/自动更正不会在点击时关闭

iOS 表格 View 。自定义单元格始终具有 320 宽度和 44 高度的内容 View

ios - Swift 3 中的不安全字节

html - 在 iOS 中打开应用程序的链接

android - Base64 图片上传在 iOS 中不起作用

ios - 如何在 UITextView 中设置文本边距?

objective-c - 在 UITextView 中只允许字母数字字符

ios - 如何在 UITextView 中插入商标符号 (TM)?

ios - MonkeyTalk 无法识别 UITextfield 输入事件

ios - 如何根据在 UITextView 中输入的文本更新 UITableViewCell 高度