如何为UITableView的分区标题添加填充?

5

如何在UITableView单元格中的节标题中添加一些填充?

我有以下内容: enter image description here

我有一个NSDictionary,其键值包含时间字符串。我将键值存储在NSArray中。

我正在使用titleForHeaderInSection而不是viewForHeaderInSection。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{   
    return [schedule objectAtIndex:section];
}

然而,章节标题全部左对齐。我可以使用UIView为viewForHeaderInSection进行填充以符合我的喜好,但有没有办法为方法titleForHeaderInSection执行此操作?

4个回答

2

我无法轻松使用titleForHeaderInSection来完成它,所以我决定使用自定义单元格和viewForHeaderInSection。


1
我认为最简单的解决方案是将标签嵌套在一个视图中。请参见下面的Swift 2答案:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    // Create the header view
    let headerView =  UIView.init(frame: CGRectMake(0, 0, self.view.frame.size.width, 30))
    headerView.backgroundColor = UIColor.lightGrayColor()

    // Create the Label 
    let label: UILabel? = UILabel(frame: CGRectMake(20, 0, 120, 30))
    label!.textAlignment = .Left
    label!.text = "Your Section Title"

    // Add the label to your headerview 
    headerView.addSubview(label)

    return headerView
}

瞧,您的文本现在有一个缩进为20的标题视图 :-D


0
最好使用tableView:viewForHeaderInSection。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 30;
}

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
      UIView *viewHeader = [UIView.alloc initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
      UILabel *lblHeadertitle = [[UILabel alloc] initWithFrame:CGRectMake(YOUR_LEFT_PADDING, YOUR_TOP_PADDING, 200, 20)];
      //customize lblHeadertitle
      lblHeadertitle.text = [schedule objectAtIndex:section];
      [viewHeader addSubview:lblHeadertitle];

      return viewHeader;
    }

但我该如何使用 viewForHeaderInSection 来显示不同的节标题? - Pangu
你可以设置lblHeadertitle.text = [schedule objectAtIndex:section]; 查看更新后的答案。 - Abhishek
不确定为什么,但是章节标题已经消失了。我尝试了多种填充方式,但都没有效果。 - Pangu
不要忘记设置 heightForHeaderInSection,参见更新的答案。 - Abhishek
某些原因导致部分标题文本偏移。无论我尝试什么填充,它总是在同一个错误的位置。请参见链接:http://s13.postimg.org/jmfqfueiv/Untitled.png - Pangu

0
基于此处所示的答案: 您有高度viewHeader = 30,lblHeadertitle = 20。
在代码中:
UILabel *lblHeadertitle = [[UILabel alloc] initWithFrame:CGRectMake(YOUR_LEFT_PADDING, YOUR_TOP_PADDING, 200, 20)];

YOUR_TOP_PADDING=5设置为5,因为lblHeadertitleviewHeader的子视图,并使其在viewHeader中居中。

希望能帮到你。


谢谢您的帮助,但是您的建议并没有起到作用,该部分标题文本完全消失了。 - Pangu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接