我正在创建一个普通的UILabel并将其设置为tableViewCell的accessoryView。我的理解是,accessoryView在单元格内保持垂直居中对齐。但这并没有发生。当我减小标签文本的字体时,附件视图会向上移动。按钮工作正常。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
}发布于 2019-12-12 17:13:19
我找到了一个解决方案。我给UILabel的帧是CGRect(x: 0,y: 0,宽: 42,高: 21)。如果我给出的高度与文本大小相同,即12.0,标签将变为居中对齐:)。这看起来像是iOS 13的问题。在iOS 12设备中未见。
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 42, height: 12))
发布于 2020-10-05 07:51:56
正如@Faizyy已经注意到的,iOS 13有一个问题,然而提供小的高度并不总是一种选择。我的方法是将UILabel放入与UILabel大小相同的UIView中,并使用该容器视图作为附件视图。这为我解决了对齐问题。下面是一个例子:
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;
}发布于 2019-12-11 23:47:12
如果您使用的是pre SwiftUI,则应考虑使用自动布局将UILabel居中放置在单元格的中央,以防止它向上移动。如果你使用的是SwiftUI,你必须使用SwiftUI布局系统。希望这能有所帮助。
https://stackoverflow.com/questions/59288974
复制相似问题