ios - UILabel作为tableViewCell的accessoryView向上移动

标签 ios swift xcode uilabel vertical-alignment

我正在创建一个普通的UILabel并将其设置为tableViewCell的accessoryView。我的理解是,accessoryView 在单元格内保持垂直居中对齐。但这并没有发生。当我减小标签文本的字体时,附件 View 会向上移动更多。按钮工作得很好。 UILabel 出现问题。

enter image description here

这是我的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    cell.textLabel?.text = "Hello"

    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 42, height: 21))
    label.backgroundColor = UIColor.red
    label.font = UIFont(name: "Helvetica Neue", size: 12)
    label.highlightedTextColor = UIColor.white
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textColor = UIColor.green
    label.textAlignment = .right;
    label.clipsToBounds = true
    label.autoresizesSubviews = true
    label.contentMode = .left
    label.text = "123";

    cell.accessoryView = label
    return cell
}

最佳答案

正如@Faizyy 所注意到的,iOS 13 存在一个问题,但是提供较小的高度并不总是一种选择。我的方法是将 UILabel 放入与 UILabel 大小相同的 UIView 中,并使用该容器 View 作为附件 View 。这为我解决了对齐问题。这是一个例子:

cell.accessoryView = [self getBadge:unread];

-(UIView *)getBadge:(int)count {
    CGFloat size = 28;
    CGFloat digits = [[@(count) stringValue] length];
    CGFloat width = MAX(size, 0.7 * size * digits);

    UILabel *badge = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, size)];
    badge.text = [@(count) stringValue];
    badge.layer.cornerRadius = size / 2;
    badge.layer.masksToBounds = YES;
    badge.textAlignment = NSTextAlignmentCenter;
    badge.font = [UIFont fontWithName:@"AvenirNext-Medium" size:16];
    badge.textColor = UIColor.whiteColor;
    badge.backgroundColor = VSColor.blue;

    UIView *badgeHolder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, size)];
    badgeHolder.backgroundColor = UIColor.clearColor;
    [badgeHolder addSubview:badge];

    return badgeHolder;
}

关于ios - UILabel作为tableViewCell的accessoryView向上移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59288974/

相关文章:

cocoa-touch - 动画 UITableViewCell ContentView 在进入编辑模式时淡入淡出

ios - Swift 4 你能用图像注释 PDF 吗

ios - 如何在较新的 Xcode 上安装较旧的 iOS 运行时?

iphone - 使用 Facebook SDK 和 Windows Azure SDK 时的 xcode 链接问题

ios - 如何从 iOS 应用程序的自定义键盘检索击键?

ios - 打破强/弱 self 的保留循环

ios - 双击主页按钮时在屏幕底部弹出。 iOS, swift

ios - 无法启动模拟器

ios - 比较数组列表和选定值并根据索引将其显示在表格 View 单元格中

swift - 不同类(class)类型