【问题标题】:Changing the spacing between textLabel and detailTextLabel in a UITableViewCell?更改 UITableViewCell 中 textLabel 和 detailTextLabel 之间的间距?
【发布时间】:2011-06-10 17:41:42
【问题描述】:

有没有一种方法可以改变 UITableViewCell 中 textLabel 和 detailTextLabel 之间的间距? (不继承 UITableViewCell)

【问题讨论】:

    标签: iphone objective-c uitableview


    【解决方案1】:

    这可以在不使用 NSAttributedString 和 attributesText 属性的情况下进行子类化,如下所示:

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyReuseIdentifier"];
    
    NSAttributedString *text = [[NSAttributedString alloc] initWithString:@"Some Text"];
    cell.textLabel.attributedText = text;
    
    NSMutableParagraphStyle *subtitleParagraphStyle = [NSMutableParagraphStyle new];
    subtitleParagraphStyle.minimumLineHeight = 20;
    
    NSMutableAttributedString *subText = [[[NSAttributedString alloc] initWithString:@"Some Subtitle Text"] mutableCopy];
    [subText addAttribute:NSParagraphStyleAttributeName value:subtitleParagraphStyle range:NSMakeRange(0, subText.length)];
    
    cell.detailTextLabel.attributedText = subText;
    

    您正在做的是强制字幕的行高大于正常值。玩弄文本和子文本的行高应该可以帮助您实现您想要的。应该兼容 iOS 7+。

    晚了几年,但希望有人觉得它有用。

    【讨论】:

      【解决方案2】:

      创建UITableViewCell 的自定义子类,并实现-layoutSubviews 方法来做到这一点:

      - (void) layoutSubviews {
        [super layoutSubviews];
        //my custom repositioning here
      }
      

      如果您想在没有子类化的情况下做到这一点,您可以通过方法调配来做到这一点,但总的来说,这是一个 Bad Idea™。

      【讨论】:

      • 没有子类化就不可能吗?
      • @iPhone 开发人员 - 是的,没有子类化是可能的,但它涉及潜入运行时并手动切换方法和东西。完全可行并且没有那么困难,但它使您的实现更加脆弱。此外,它会影响您应用中的每个 UITableViewCell,而不是只影响这里和那里的几个。
      • @iPhone 开发人员:如果您需要更改默认的 UITableViewCell,子类化始终是最好的方法。 @Dave:很好的解释。