ios - NSTextAlignmentCenter无法与UITableViewCellStyleSubtitle一起使用

标签 ios uitableview

当单元格样式为默认时,NSTextAlignment有效,但是当我将其更改为字幕时,它不起作用。

cell.textLabel.textAlignment=NSTextAlignmentCenter;

最佳答案

您无法更改单元格字幕标签的NSTextAlignment。原因是此标签仅与文本一样宽。如果您不相信我,可以尝试设置它的背景色:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.backgroundColor = [UIColor orangeColor];
}

因此,您可以看到UILabel根据其中的文本更改了宽度。

官方文件也违背了它的规定:

单元格的样式,顶部带有左对齐的标签,
下方的左对齐标签,以较小的灰色文本显示。 iPod应用程序
使用这种样式的单元格。

因此,我可以建议三种实现目标的不同方法:

第一种方式

您可以按照以下教程创建自己的定制单元:
  • appcoda.com
  • codigator.com

  • 您可以自己添加标题标签和字幕,并设置它们的所有属性。

    第二种方式

    这是另一个解决方法,如果您不想实现自定义单元,则可以使用它。只需使用以下方法:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        UILabel *myLabel;
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    
            myLabel = [[UILabel alloc] initWithFrame:CGRectMake(yourX, yourY, yourWidth, yourHeight)];
            myLabel.tag = 1;
            myLabel.textAlignment= UITextAlignmentCenter;
    
            [cell.contentView addSubview:myLabel];
        }
    
        myLabel = (UILabel*)[cell.contentView viewWithTag:1];
        //Add text to it
        myLabel.text = [myArray objectAtIndex:indexPath.row];
    
        return cell;
    }
    

    第三路

    您可以实现方法,该方法将在渲染后更改单元格字幕标签的文本对齐方式。绝对不是最好的解决方案,但是如果您愿意,可以尝试一下:
    - (void) updateCenteringForTextLabelInCell:(UITableViewCell*)cell 
    {
        UILabel *myLabel = cell.textLabel;
        myLabel.frame = CGRectMake(myLabel.frame.origin.x, myLabel.frame.origin.y, cell.contentView.frame.size.width, myLabel.frame.size.height);
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //use your already implemented code
        [self performSelector:@selector(updateCenteringForTextLabelInCell:) withObject:cell afterDelay:0.05];
    }
    

    摘要:

    我建议您使用第一种方法,因为所有其他方法都有些棘手。除此之外,您以后可以在自定义单元中添加很多不同的元素,这可能非常有用。

    关于ios - NSTextAlignmentCenter无法与UITableViewCellStyleSubtitle一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614465/

    相关文章:

    ios - 通过 plist 的 TableView 部分

    ios - NSOperation 执行失败

    ios - UITableView 中未调用 didSelectRowAtIndexPath

    ios - UIPageViewController 手势正在调用 viewControllerAfter : but doesn't animate

    objective-c - 如何消除分组UITableView的左右边距

    cocoa-touch - 为什么表格 View 单元格中的自动布局会导致表格的内容大小错误地更改?

    ios - AVAudioPCMBuffer - 读取(进入缓冲区 : AVAudioPCMBuffer) memory crash?(缓冲区溢出)

    ios - xcuitest- 尝试点击链接标签中的链接

    ios - 调整包含多个 View 的 iOS 表格 View 单元格的大小

    ios - indexPath 为 tableView 单元格中的自定义 UISwitch 返回 null?