How do I Truncate middle of String based on conditions in UILabel in Swift iOS?

49 Views Asked by At

I have a String like this : AU 6,7,8,9,10,11,...,20,21,22,23,24,25 refer this image

I have to fill only 8 sizes. This sizes have no limit they can be more than 20 or 50 also. If there are only 8 sizes available, show AU 6, 7, 8, 9, 10, 11, 12 ,13 If there are more than 8 sizes, show AU 6, 7, 8, 9, 10, 11 ... 25. Three dots in front of the last size only.

I have given 1 number of lines to the UILabel and Link Break is Truncate Middle.

I'm very new to swift and I have no idea how do I achieve this ? I would be grateful for your help. Thank You !

1

There are 1 best solutions below

2
lazarevzubov On BEST ANSWER

I think the requirement is not achievable by means on SwiftUI only. An algorithm that generates a string out of an array of sizes (integers) should help. For instance:

func makeSizesString(sizesArray: [Int]) -> String {
  if (sizesArray.count <= 8) {
    sizesArray.map { "\($0)" }.joined(separator: ", ")
  } else {
    sizesArray[...5].map { "\($0)" }.joined(separator: ", ") + " ... \(sizesArray[sizesArray.count - 1])"
  }
}

print(makeSizesString(sizesArray: [1, 2, 3, 4, 5, 6, 7])) // 1, 2, 3, 4, 5, 6, 7
print(makeSizesString(sizesArray: [1, 2, 3, 4, 5, 6, 7, 8])) // 1, 2, 3, 4, 5, 6, 7, 8
print(makeSizesString(sizesArray: [1, 2, 3, 4, 5, 6, 7, 8, 9])) // 1, 2, 3, 4, 5, 6 ... 9
print(makeSizesString(sizesArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) // 1, 2, 3, 4, 5, 6 ... 10