简体   繁体   中英

Two Lines in UITableViewCell's textLabel with new line being determined ONLY by newline character in text

I want to format a cell's textLabel to display text on two lines, with a line break character determining where the second line will begin. My problem is that, since I do not control the text that will be in the first line, sometimes the text on the first line spills over to the second line and my second line text does not display at all. Specifying UILineBreakModeWordWrap actually sometimes even breaks a word in two to wrap it, which makes no sense (I use the first line for names). I need two lines and two lines only for this label, as that is all there is room for in this particular cell. I am already using the detailTextLabel for something else. I really do not want to create a custom cell for this. Is it possible to do what I am asking?

Here's what you COULD do:

You could take your long string, split into two with componentsSeparatedByString, take each piece, use an iterative sizeWithFont:constrainedToSize:lineBreakMode to calculate the longest string that fits with the default textLabel width, then take your two newly crafted strings and append them with a '\\n' character. Use that as your textLabel text.

That should achieve what you're trying to do. But what I HIGHLY recommend to you is that you do yourself a favor and go custom. For a number of reasons:

  1. Yes, custom cells typically do take longer to create. But, I'd argue that in this particular case, it would be faster to go custom than to implement the above. The implementation above doesn't even account for ellipses at the ends of truncated strings. You can throw that into the mix, but that's just gonna add even more time and complexity. With custom cells and individual labels, something like this becomes a gimme.
  2. Custom allows you to easily give your two lines of text their own fonts/sizes. Using IB, basic styling on these fields becomes a breeze. And that's a pretty slick bonus. For your users especially. You mention that the first line of text is for names - why not make it bold to better distinguish it from the second line of text?
  3. If you plan on creating and releasing iOS apps in the future, you're gonna be making A LOT of custom cells. Why not use this one as practice?

If you need guidance on creating custom cells, this is a pretty thorough tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM