How do I add tab stops to an NSAttributedString and display in a UITextView
In iOS 7 you can do it like this:
UIFont *font = [UIFont systemFontOfSize:18.0];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
NSInteger cnt;
CGFloat tabInterval = 72.0;
paragraphStyle.defaultTabInterval = tabInterval;
NSMutableArray *tabs = [NSMutableArray array];
for (cnt = 1; cnt < 13; cnt++) { // Add 12 tab stops, at desired intervals...
[tabs addObject:[[NSTextTab alloc] initWithTextAlignment:NSTextAlignmentLeft location:tabInterval * cnt options:nil]];
}
paragraphStyle.tabStops = tabs;
NSDictionary *attributes = @{ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle};
This is the Swift version that worked for me:
let tablInterval: CGFloat = 85.0
let paragraphStyle = NSMutableParagraphStyle()
let terms = NSTextTab.columnTerminatorsForLocale(NSLocale.currentLocale())
let tabStop0 = NSTextTab(textAlignment: .Right, location: 0, options: [NSTabColumnTerminatorsAttributeName:terms])
let tabStop1 = NSTextTab(textAlignment: .Right, location: tablInterval, options: [NSTabColumnTerminatorsAttributeName:terms])
let tabStop2 = NSTextTab(textAlignment: .Right, location: tablInterval*2, options: [NSTabColumnTerminatorsAttributeName:terms])
let tabStop3 = NSTextTab(textAlignment: .Right, location: tablInterval*3, options: [NSTabColumnTerminatorsAttributeName:terms])
paragraphStyle.addTabStop(tabStop0)
paragraphStyle.addTabStop(tabStop1)
paragraphStyle.addTabStop(tabStop2)
paragraphStyle.addTabStop(tabStop3)
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:rangeAll)