0

Examples (x=1):

ABC -> ABC
ABCDEFGHIJKL -> ABCDE...L
ABCDEFGHIJKLMNOPQRS -> ABCDE...S

(truncating after 5 characters is an arbitrary choice for this question - it will depend on the width of the label of course)

I'm basically looking for the same functionality as truncating in the middle, but where I can specify how many characters to leave on the trailing end. Is this available in Swift or is there a reasonable workaround?

AJP
  • 57
  • 4
  • 1
    Well it isn't built in or anything like that. If you want to just change the string to substitute dots where you want them, then that's up to you. – matt Oct 15 '20 at 19:20
  • Yes, I could. However, how would I determine "where I want them" given strings with varying lengths? – AJP Oct 15 '20 at 19:26
  • You can measure the string (i.e. in pixel width) – matt Oct 15 '20 at 19:32
  • After almost an hour, I am failing to translate this to code. Care to give a hint on how to start (words or code)? – AJP Oct 15 '20 at 20:23
  • For example https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrect and https://developer.apple.com/documentation/foundation/nsstring/1531844-size ? – matt Oct 15 '20 at 20:46
  • You can get a lot more sophisticated by drawing with TextKit. But basically whatever you do here, you are rolling your own; what you ask for is not built in – matt Oct 15 '20 at 20:49

1 Answers1

1

You can measure any string with .size(withAttributes:) function. Where attributes is your font.

Here is the idea:

  1. get length of the last x characters plus dots symbol
  2. iteratively measure the string starting from the beginning and adding 1 char on each step
  3. if width of the leading string plus tail excess the given width, take just the string from the previous step.