How can I crop text in a UITableView Cell TextLabel so that it doesn't hide the DetailTextLabel?

I have a list of phone rates, textLabel is the country / territory, and detailTextLabel is the speed I should display.

For some lines, the textLabel too long, and the detailTextLabel hidden. Is there a way to automatically adjust the text with … if it is too long?

Here is an example where Central African Republic (Mobile) has this problem:

example

+5
source share
2 answers

When placing a cell of type UITableViewCellStyle.Value1, the title bar seems to take priority and pushes the part label out of view. The solution may 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 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 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 } } } } 

Please note that although detail.textAlignment = .Left we take into account the width of the part, and the actual text ends to the right.

+3
source

So you probably need to manually fix the width of the textLabel, since by default it takes up the entire width of the cell. To do this, you can do the following:

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

In your cellForRowAtIndexPath, where DETAIL_LABEL_WIDTH is the width you want for detailTextLabel. Assuming the label is an automatic ellipse, which should be, this will cause the text to add β€œ...” at the end of the label, immediately before the label of the part text, if the width is greater than the width you set above,

0
source

Source: https://habr.com/ru/post/1200320/


All Articles