NeXT5tep
NeXT5tep

Reputation: 881

How do i get the range of the current paragraph in a NSTextView where the cussor stayed there?

Now i need to change the alignment of a paragraph in a nstextview without select it ,so i need to know the range of the current range of the paragraph?

Upvotes: 0

Views: 1317

Answers (3)

Vitalii Vashchenko
Vitalii Vashchenko

Reputation: 1817

Here's a shortcut:

NSRange paragraphRange = [textView.textStorage.string paragraphRangeForRange: [textView selectedRange]];

Upvotes: 2

Afarfly
Afarfly

Reputation: 59

First, get the range where the cursor stayed through [textView selectedRange]
Then you can get the line range through - (NSRange)lineRangeForRange:(NSRange)range of [textView string]

Here is a example code:

NSRange sel = [textView selectedRange];
NSString *viewContent = [textView string];
NSRange lineRange = [viewContent lineRangeForRange:NSMakeRange(sel.location,0)];

detail in there. How to get the selected line range of NSTextView?

Upvotes: -1

user207616
user207616

Reputation:

I have a subclass of NSTextView so you need to access textStorage and selectedRange different than [self textStorage] and [self selectedRange].

NSTextStorage *textStorage = [self textStorage];
NSString *string = [textStorage string];

NSUInteger editEnd = [self selectedRange].location;
NSUInteger editStart = editEnd-[textStorage editedRange].length;
NSUInteger maxLength = [string length];


while (editStart > 0) {
    unichar theChr = [string characterAtIndex:editStart-1];
    if( theChr == '\n' || theChr == '\r' ) {
        break;
    }
    --editStart;
}
while (editEnd < maxLength) {
    unichar theChr = [string characterAtIndex:editEnd];
    if( theChr == '\n' || theChr == '\r' ) {
        break;
    }
    ++editEnd;
}

NSRange paragraphRange = NSMakeRange(editStart, editEnd-editStart);

Upvotes: 2

Related Questions