Hi, ALL,
My first post here, so please be gentle... ;-)
I'm trying to apply the left indentation to the NSTextView. So, I wrote following code:
(I know it is inefficient, but I need to make it work first)
NSMutableParagraphStyle *paragraphStyle;
double indent = 100 * mm2pt / 10.0;
if ( start == -1 && end == -1 ) // no selection, control is either empty or contain some text
{
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setHeadIndent: indent];
[paragraphStyle setFirstLineHeadIndent: indent];
[m_textView setDefaultParagraphStyle:paragraphStyle];
[paragraphStyle release];
}
else // Set the attributes just for the selection
{
NSRange range = NSMakeRange(start, end-start);
NSTextStorage* storage = [m_textView textStorage];
paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setFirstLineHeadIndent: indent];
[paragraphStyle setHeadIndent: indent];
[storage addAttribute: NSParagraphStyleAttributeName value: paragraphStyle range: range];
[paragraphStyle release];
}
The problem is that if I don't have a selection, I don't see any indentation applied. Going thru the code with debugger,
the code is executed successfully. No errors or exceptions. But if the selection is present, everything works and the text
is left indented.
My question is: is setDefaultParagraphStyle() a correct function to use? And if yes - do I need some other call inside the if
clause? I want this code to work even on the empty text view.
I'm testing on OSX 10.8 with Xcode 5. And the minimum OSX version is 10.7.
Thank you.
The numbers in NSMakeRange are the start and length, not the start and end. So if storage.string.length is 200, you're trying to change characters beyond the end of the text (200, 201, 202, … 399), which obviously can't work.
You should use something like NSMakeRange (insPoint, storage.string.length - insPoint), but you should always check that insPoint isn't larger than storage.string.length — a negative length is also going to crash.