如何截断 UITableView Cell TextLabel 中的文本,使其不隐藏 DetailTextLabel? [英] How can I truncate text in a UITableView Cell TextLabel so it doesn't hide the DetailTextLabel?
问题描述
我有一个电话费率列表,textLabel
是国家/地区,detailTextLabel
是我必须显示的费率.
I have a list of phone rates, the textLabel
is the country/territory and the detailTextLabel
is the rate I have to display.
对于某些字符串,textLabel
太长,detailTextLabel
被隐藏.如果文本太长,是否有设置可以使用 ...
自动调整文本?
For some strings, the textLabel
is too long and the detailTextLabel
becomes hidden. Is there a setting to automatically adjust the text with …
if it's too long?
以下是中非共和国(移动)
存在此问题的示例:
Here is an example where Central African Republic (Mobile)
has this issue:
推荐答案
在布局具有 UITableViewCellStyle.Value1 样式的单元格时,标题标签似乎获得优先权并将细节标签推到视野之外.解决方案可能是继承 UITableViewCell 并覆盖其 layoutSubviews():
On laying out a cell with UITableViewCellStyle.Value1 style the title label seems to get priority and push the detail label out of view. The solution might be to subclass UITableViewCell and override its 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
我们考虑了细节的宽度,但实际文本最终会向右对齐.
Note that although detail.textAlignment = .Left
we account for detail's width and the actual text ends up aligned to the right.
这篇关于如何截断 UITableView Cell TextLabel 中的文本,使其不隐藏 DetailTextLabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!