Decrease the width of the last line in multiline UILabel

前端 未结 6 1917
谎友^
谎友^ 2020-12-04 18:19

I am implemententing a \"read more\" functionality much like the one in Apple\'s AppStore. However, I am using a multiline UILabel. Looking at Apple\'s AppStore

6条回答
  •  情话喂你
    2020-12-04 18:52

    @paul-slm's answer above is what I ended up using, however I found that it is a very intensive process to strip away the last character of a potentially long string one by one until the label fits the required number of lines. Instead it makes more sense to copy over one character at a time from the beginning of the original string to a blank string, until the required number of lines are met. You should also consider not stepping by one character at a time, but by multiple characters at a time, so as to reach the 'sweet spot' sooner. I replaced func getTruncatingText() -> String with the following:

    private func getTruncatingText() -> String? {
        guard let originalString = originalString else { return nil }
    
        if numberOfLinesNeeded(originalString) > collapsedNumberOfLines {
            var truncatedString = ""
            var toyString = originalString
            while numberOfLinesNeeded(truncatedString + ellipsis) != (collapsedNumberOfLines + 1) {
                let toAdd = toyString.startIndex.. collapsedNumberOfLines {
                truncatedString.removeSubrange(truncatedString.index(truncatedString.endIndex, offsetBy: -1)..

提交回复
热议问题