Skip to content

Instantly share code, notes, and snippets.

@anoop4real
Created April 6, 2020 15:13
Show Gist options
  • Save anoop4real/dc6e84bc200b918c5bb6e0788837eb01 to your computer and use it in GitHub Desktop.
Save anoop4real/dc6e84bc200b918c5bb6e0788837eb01 to your computer and use it in GitHub Desktop.
A Swift string extension for adding leading ellipsis
extension String {
func stringByTruncatingLeadingForWidth(width: CGFloat, withFont font: UIFont) -> String{
var modifiedString = self
var mutableWidth = width
let ellipsis = "..."
if (self.widthOfString(usingFont: font) > width) {
let ellipsisWidth = ellipsis.widthOfString(usingFont: font)
// else this will go for infinite loop...mutable width will go -ve
if mutableWidth > ellipsisWidth {
mutableWidth -= ellipsis.widthOfString(usingFont: font)
}
let range = NSMakeRange(0, 1)
while modifiedString.widthOfString(usingFont: font) > mutableWidth {
modifiedString.deleteCharactersInRange(range: range)
print(modifiedString)
print(mutableWidth)
}
guard let swiftRange = Range(NSMakeRange(0, 3), in: modifiedString) else { return "" }
modifiedString.replaceSubrange(swiftRange, with: [".",".","."])
}
return modifiedString
}
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
mutating func deleteCharactersInRange(range: NSRange) {
guard let swiftRange = Range(range, in: self) else { return }
self.removeSubrange(swiftRange)
}
}
var str1 = "Hello how are you"
let newStr = str1.stringByTruncatingLeadingForWidth(width: 100, withFont: .systemFont(ofSize: 15))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment