Search code examples
swiftstringuikituilabel

How to limit UILabel's max characters


I want to limit UILabel.text in 8 Chinese word or 16 English word, and if the text is larger than this, use "..." to replace the redundant place.

I tried to count String size, but I don't know how to deal with both English words and Chinese words. Because is I count bytes by utf8, the Chinese word would be triple than English words. (Considering the label might have both Chinese word and English words, it's hard to calculate.)

for example:

1."Batman like cat Woman and Alfred." should look like "Batman like cat..."

2."蝙蝠侠喜欢猫女和阿福" should look like "蝙蝠侠喜欢猫女和..."

3."Batman喜欢猫女和阿福" should look like "Batman喜欢猫女和..."

I know Android has a property to do this, how about Swift?

Lookingforward for your response, and sorry for my poor English description.


Solution

  • You can iterate your string indices counting the characters, if it is a chinese character add 2 otherwise add 1. If the count is equal to 16 return the substring up to the current index with "…" at the end. Something like:

    extension Character {
        var isChinese: Bool {
            String(self).range(of: "\\p{Han}", options: .regularExpression) != nil
        }
    }
    

    extension StringProtocol {
        var limitedLenghtLabelText: String {
            var count = 0
            for index in indices {
                count += self[index].isChinese ? 2 : 1
                if count == 16 {
                    let upperBound = self.index(after: index)
                    return String(self[..<upperBound]) + (upperBound < endIndex ? "…" : "") }
            }
            return String(self)
        }
    }
    

    "蝙蝠侠喜欢猫女和阿福".limitedLenghtLabelText   // "蝙蝠侠喜欢猫女和…"
    
    "Batman喜欢猫女和阿福".limitedLenghtLabelText  // "Batman喜欢猫女和…"