Skip to content

Instantly share code, notes, and snippets.

@Nirma
Last active Aug 28, 2015
Embed
What would you like to do?
import UIKit
extension String {
var length: Int {return count(self)}
}
func nextBinaryTrialIndex(seriesSize: Int, index: Int, pass: Bool) -> Int? {
//Error No case exists
if index >= seriesSize || index <= 0 {
return nil
}
//base case 1
if pass && index == (seriesSize - 1) {
return index
}
return pass ? (((seriesSize - index) / 2) + 1) : seriesSize / 2
}
func textWillTruncate(text: String, textBounds: CGSize, font: UIFont?) -> Bool {
let font = font ?? UIFont.systemFontOfSize(UIFont.systemFontSize())
let fontSize = (text as NSString).sizeWithAttributes([NSFontAttributeName: font])
return (fontSize.height > textBounds.height || fontSize.width > textBounds.width)
}
func trailingString(string: String, charLimit: Int) -> String {
let trailingString = "***"
let trailingStringSize = trailingString.length
if string.length < trailingStringSize + 1 || charLimit < 4 {
return string
}
let limitedString = string.substringToIndex(advance(string.startIndex, charLimit))
return string.substringToIndex(advance(limitedString.endIndex, -trailingStringSize)) + trailingString
}
func smartTrailingString(let trailingLabel: UILabel, targetSubString: String) -> String {
let originalText = trailingLabel.text ?? ""
let font = trailingLabel.font
let bounds = trailingLabel.bounds.size
var result = originalText
if !textWillTruncate(originalText, bounds, font) {
return originalText
}
var targetStringLimit = targetSubString.length
var pass = false
var nextText: String
do {
let eliptifiedString = trailingString(targetSubString, targetStringLimit)
nextText = originalText.stringByReplacingOccurrencesOfString(targetSubString, withString: eliptifiedString)
pass = !textWillTruncate(nextText, bounds, font)
if pass {
break
} else {
targetStringLimit -= 1
}
} while targetStringLimit > 0
return nextText
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment