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