3

Is there a Swift way of getting rid of the ellipsis (...) in a label with a lineBreakingMode set to either ByTruncatingHead or ByTruncatingTail?

I've run into an Obj-C way and tried to convert it to swift but to no avail (I failed miserably). Any help or hints are greatly appreciated.

Here's my conversion:

private func replaceElipses() {
        let origSize = self.frame
        let useWidth = origSize.size.width

        self.sizeToFit()

        let labelSize = (self.text! as NSString).sizeWithAttributes([NSFontAttributeName: self.font])

        if labelSize.width > useWidth {
            original = self.text!
            truncateWidth = useWidth
            systemfont = self.font
            subLength = (self.text?.characters.count)!

            var temp = ((self.text)! as NSString).substringToIndex(self.text!.characters.count-1) as NSString
            temp = temp.substringToIndex(self.getTruncatedStringPoint(subLength))
            temp = "\(temp)\("@")"

            var count = 0
            while (self.text! as NSString).sizeWithAttributes([NSFontAttributeName: self.font]).width > useWidth {
                count++
                temp = ((self.text)! as NSString).substringToIndex(self.text!.characters.count-(1+count)) as NSString
                temp = "\(temp)\("@")"
            }
            self.text = temp as String
            self.frame = origSize

        } else {
            self.frame = origSize
        }
    }

    func getTruncatedStringPoint(splitPoint: Int) -> Int {
        let splitLeft = original.substringToIndex(splitPoint) as NSString
        subLength /= 2

        if subLength <= 0 {
            return splitPoint
        } else if splitLeft.sizeWithAttributes([NSFontAttributeName: systemfont]).width > truncateWidth {
            return self.getTruncatedStringPoint(splitPoint - subLength)
        } else if splitLeft.sizeWithAttributes([NSFontAttributeName: systemfont]).width < truncateWidth {
            return self.getTruncatedStringPoint(splitPoint + subLength)
        } else {
            return splitPoint
        }
    }
Community
  • 1
  • 1
cyril
  • 3,020
  • 6
  • 36
  • 61
  • Show how you tried to convert it and explain what your conversion does wrong – Wain Dec 22 '15 at 11:40
  • I converted the code line by line albeit with a few modifications (updated my answer to reflect it) and nothing happens. Yes, it is being called :( @Wain – cyril Dec 22 '15 at 12:20

0 Answers0