The issue here is that NSTextView has a default NSMutableParagraphStyle object which has a list of attributes such as line wrapping, tab stops, margins, etc... You can see this by going to the Format menu, text subview, and select the "Show Ruler" menu. (You get this menu for free with any NSTextView).
Once you show the ruler you will see all of your tab stops and this will explain why your tabs are wrapping once you reach the last tab stop.
So the solution you need is to create an array of tabs that you want for your paragraph style object and then set that to be the style for the NSTextView.
Here is a method to create tabs. In this example, it will create 5 left aligned tabs, each 1.5 inches apart:
-(NSMutableAttributedString *) textViewTabFormatter:(NSString *)aString
{
float columnWidthInInches = 1.5f;
float pointsPerInch = 72.0f;
NSMutableArray * tabArray = [NSMutableArray arrayWithCapacity:5];
for(NSInteger tabCounter = 0; tabCounter < 5; tabCounter++)
{
NSTextTab * aTab = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:(tabCounter * columnWidthInInches * pointsPerInch)];
[tabArray addObject:aTab];
}
NSMutableParagraphStyle * aMutableParagraphStyle = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];
[aMutableParagraphStyle setTabStops:tabArray];
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:aString];
[attributedString addAttribute:NSParagraphStyleAttributeName value:aMutableParagraphStyle range:NSMakeRange(0,[aString length])];
return attributedString;
}
Then you invoke it before you add any text to your NSTextView in order to set the default paragraph style with those tab stops in it:
[[mainTextView textStorage] setAttributedString:[self textViewTabFormatter:@" "]];
You can find a additional informatio here, if you want a deeper tutorial:
http://www.mactech.com/articles/mactech/Vol.19/19.08/NSParagraphStyle/index.html
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…