【问题标题】:Center vertically UILabel text in table view section header在表格视图部分标题中垂直居中 UILabel 文本
【发布时间】:2013-01-23 15:31:57
【问题描述】:

如何更改表格视图部分中文本的位置?我使用 viewForHeaderInSection:Section 并在那里创建这样的东西:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
    label.backgroundColor = [UIColor blackColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"Gotham-Bold" size:17.0f];

    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.comlpetedFetchedResultsController sections] objectAtIndex:section];
    label.text = [@" " stringByAppendingString:[sectionInfo name]];
    return label;
}

UILabel 框架中的参数大小无关紧要,我总是得到相同的结果:

如何在 UILabel 中垂直居中文本? 谢谢

【问题讨论】:

  • 你可以看到文字在黑色UILabel的顶部,我想让它居中(现在稍微往下一点)
  • 您是否尝试使用 label 将标签中的文本居中。 textAlignment =UITextAlignmentCenter
  • 你尝试改变 y 吗? UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 3, 300, 30)];
  • @Simone 是的,我试过了,没用。
  • 好的,如果你创建了一个 UIView,并把 UILabel 放在它上面并改变了 y 并返回 UIView 而不是 UILabel?

标签: iphone ios uitableview


【解决方案1】:

试试

[yourLabel setNumberOfLines:0];
[yourLabel sizeToFit];
[yourLabel setContentMode:UIViewContentModeCenter];

【讨论】:

    【解决方案2】:

    将标签放在 UIView 中,然后返回视图:

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
    [view addSubview:label];
    return view;
    

    确保实现以下方法:

    -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
    

    否则您的视图将仅位于单元格顶部。

    【讨论】:

      【解决方案3】:

      通过此链接:NSTextAlignment

      下面给出的还有代码sn-p,可能对你有帮助

        UILabel *myLabel = [[UILabel alloc] init];
      
        [myLabel setText:@"Abc"];
        [myLabel setTextAlignment:NSTextAlignmentCenter];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-26
        • 2015-08-25
        • 2012-03-12
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-20
        相关资源
        最近更新 更多