如何添加表格视图节标题与下标?

在我的应用程序中,我有一个表格视图,到目前为止我已经使用storyboard(我已经添加了部分:rows:cells等等,全部通过storyboard),唯一的改变是编程式的添加一个UIButton作为部分标题通过执行:

 - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { if (section == 2) { UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)]; UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button1 setTitle:@"Hydro Volume" forState:UIControlStateNormal]; button1.frame = CGRectMake(62.5, 5, 205, 44); [view addSubview:button1]; [button1 addTarget: self action: @selector(buttonClicked:) forControlEvents: UIControlEventTouchDown]; return view; } return nil; } 

我目前的困境是,我不得不添加一个包含下标的节标题,即:H2O 化学公式的图像与下标

我无法直接在故事板检查器中添加下标,有人可以告诉我怎么做到这一点?

我回顾了这个问题 ,但它不是我正在寻找的,因为我需要能够将其添加到我的部分标题。

一个简单的解决scheme是使用Unicode下标范围U + 2080到U + 2089。 例如:2 H 2 + O 2→2 H 2 O.

您可以使用Unicodehexinput键盘布局,保留选项,并键入hex数字(例如保持选项,并键入“2080”为“〇”)键入这些字符之一。

给定一个数字,你可以把它格式化为一个string,如下所示:

 static const unichar kSubscriptZero = 0x2080; int numberOfHydrogens = 2; NSString *water = [NSString stringWithFormat:@"H%CO", kSubscriptZero + numberOfHydrogens]; 

http://www.unicode.org/charts/PDF/U2070.pdf

我认为这是你使用属性string要做的事情的要点。 我目前没有Xcode在我面前,所以可能有错误:

 if (section == whicheverSectionIndexIsCorrect) { NSString *plainText = @"2H2 + O2 → 2H2O"; id subscriptOffset = @(-0.5); // random guess here, adjust offset as needed NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:plainText]; // apply attributes for each character to subscript [text addAttribute:(NSString *)kCTSuperscriptAttributeName value:subscriptOffset range:NSMakeRange(2, 1)]; [text addAttribute:(NSString *)kCTSuperscriptAttributeName value:subscriptOffset range:NSMakeRange(7, 1)]; // etc. UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)]; UILabel *label = [[UILabel alloc] init]; label.attributedText = text; [view addSubview:label]; return view; } 

编辑:可能只适用于OS X:我也注意到,有NSAttributedString初始化器采取HTML 。 我没有使用过,所以不能说它是否会工作,但如果它在iOS中工作并理解下标,那么如果您从数据存储加载这些下标标签而不是硬编码它们可能会更简单。