I managed to solve this problem. This is not the most beautiful code, but it works. I return the word number from the last line of the label, from which I can calculate the width from which the text ends, and the image begins to count (x, y).
func lastWordInTitle(title: String) -> Int { var separateWords: [String] = [] var sizeOfWords: [CGFloat] = [] var wordsRemaining: Int = 0 var wordsWidthInOneLine: CGFloat = 0 let font = titleLabel.font let fontAttr = [NSAttributedStringKey.font: font] title.enumerateSubstrings(in: title.startIndex..<title.endIndex, options: .byWords) { (substring, _, _, _) in if let substring = substring { separateWords.append(substring) // number of words in label sizeOfWords.append(substring.size(withAttributes: fontAttr).width + 8) //size of each word + 8 for the space between them } } wordsRemaining = separateWords.count print("SSS wordsRemaining initial \(wordsRemaining)") var wordsToRemoveIndex = 0 for index in 0..<separateWords.count { wordsWidthInOneLine += sizeOfWords[index] wordsToRemoveIndex += 1 if wordsWidthInOneLine > titleLabel.frame.width { if index == separateWords.count - 1 { wordsRemaining -= wordsToRemoveIndex return 1 } else { wordsRemaining -= wordsToRemoveIndex - 1 == 0 ? 1 : wordsToRemoveIndex - 1 wordsToRemoveIndex = 0 wordsWidthInOneLine = 0 wordsWidthInOneLine = sizeOfWords[index] } } else if wordsWidthInOneLine < titleLabel.frame.width && index == separateWords.count - 1 { let reversedSeparateWordsSize = Array(sizeOfWords.reversed()) var width: CGFloat = 0 for index in 0..<wordsRemaining { width += reversedSeparateWordsSize[index] } if width > titleLabel.frame.width { return wordsRemaining - 1 } return wordsRemaining } } return wordsRemaining }
source share