1
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) 範囲配列の取得 - (void)analyse { if (self.mRangesArray != nil) { [self.mRangesArray removeAllObjects]; } NSString *string = self.text; NSUInteger numberOfLines, index, 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;
              }
        }
    }];

}

助けてくれてありがとう。乾杯 :)

4

2 に答える 2

2

編集:あなたの質問の現在選択されている部分を明らかに無視しました。誰かが必要とする場合に備えて、ここにコードを残しておきます。

改行区切りを数えてみましたか?

let str = "First\nSecond\nThird"
let tok = str.componentsSeparatedByString("\n")
print(tok.count) // Hopefully prints "3"
于 2016-05-23T13:44:22.293 に答える
0

動作するこのコードを試してください

UIFont * fontNAme = [UIFont boldSystemFontOfSize:13.0]; 
CGSize size = [textView.text fontNAme  constrainedToSize:textView.frame.size  lineBreakMode:UILineBreakModeWordWrap]; 
int lineNumber = size.height / fontNAme .lineHeight;
NSLog(@"line = %d", lineNumber);
于 2016-05-23T13:00:24.710 に答える