如何截断UITableView Cell TextLabel中的文本,以便它不会隐藏DetailTextLabel?

我有一个电话费率列表, textLabel是国家/地区, detailTextLabel是我必须显示的费率。

对于某些字符串, textLabel太长并且detailTextLabel变为隐藏状态。 是否有设置自动调整文本如果它太长了?

以下是Central African Republic (Mobile)有此问题的例子:

例

在布置具有UITableViewCellStyle.Value1样式的单元格时,标题标签似乎优先,并将详细标签推出视图。 解决方案可能是子类UITableViewCell并覆盖其layoutSubviews():

  override func layoutSubviews() { super.layoutSubviews() if let detail = self.detailTextLabel { // this will do the actual layout of the detail // label's text, so you can get its width detail.sizeToFit() // you might want to find a clever way to calculate this // instead of assigning a literal let rightMargin: CGFloat = 16 // adjust the detail's frame let detailWidth = rightMargin + detail.frame.size.width detail.frame.origin.x = self.frame.size.width - detailWidth detail.frame.size.width = detailWidth detail.textAlignment = .Left // now truncate the title label if let text = self.textLabel { if text.frame.origin.x + text.frame.size.width > self.frame.width - detailWidth { text.frame.size.width = self.frame.width - detailWidth - text.frame.origin.x } } } } 

请注意,虽然detail.textAlignment = .Left我们考虑了细节的宽度,实际文本最终与右边对齐。

所以你可能需要做的是手动修复textLabel的宽度,因为默认情况下它会占用单元格的整个宽度。 为此,您可以执行以下操作:

 CGRect textLabelFrame = cell.textLabel.frame; textLabelFrame.size.width -= DETAIL_LABEL_WIDTH; cell.textLabel.frame = textLabelFrame; 

在您的cellForRowAtIndexPath中,DETAIL_LABEL_WIDTH是detailTextLabel所需的宽度。 假设标签是自动椭圆化的,它应该是,如果宽度超过您在上面设置的宽度,这将导致文本在细节文本标签之前的标签末尾添加“…” 。