Skip to content

Instantly share code, notes, and snippets.

@christianascone
Created June 21, 2017 10:51
Show Gist options
  • Save christianascone/9deab6921c720cf5d25b9a4478077668 to your computer and use it in GitHub Desktop.
Save christianascone/9deab6921c720cf5d25b9a4478077668 to your computer and use it in GitHub Desktop.
UILabel extension for truncated state
//
// UILabel+Extension.swift
// ShopAdvisor
//
// Created by Christian Ascone on 21/06/2017.
// Copyright © 2017 Luna srls. All rights reserved.
//
import Foundation
extension UILabel {
/// Check if this uilabel has been truncated
///
/// - Returns: true if label has been truncated, false otherwise
func isTruncated() -> Bool {
if let string = self.text {
let size: CGSize = (string as NSString).boundingRect(
with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.font],
context: nil).size
return (size.height > self.bounds.size.height)
}
return false
}
/// Gets length of visible text of this uilabel
///
/// - Returns: characters count of visible characters
func visibleTextLength() -> Int {
let font: UIFont = self.font
let mode: NSLineBreakMode = self.lineBreakMode
let labelWidth: CGFloat = self.frame.size.width
let labelHeight: CGFloat = self.frame.size.height
let sizeConstraint = CGSize(width: labelWidth, height: CGFloat.greatestFiniteMagnitude)
let attributes: [AnyHashable: Any] = [NSFontAttributeName: font]
let attributedText = NSAttributedString(string: self.text!, attributes: attributes as? [String : Any])
let boundingRect: CGRect = attributedText.boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, context: nil)
if boundingRect.size.height > labelHeight {
var index: Int = 0
var prev: Int = 0
let characterSet = CharacterSet.whitespacesAndNewlines
repeat {
prev = index
if mode == NSLineBreakMode.byCharWrapping {
index += 1
} else {
index = (self.text! as NSString).rangeOfCharacter(from: characterSet, options: [], range: NSRange(location: index + 1, length: self.text!.characters.count - index - 1)).location
}
} while index != NSNotFound && index < self.text!.characters.count && (self.text! as NSString).substring(to: index).boundingRect(with: sizeConstraint, options: .usesLineFragmentOrigin, attributes: attributes as? [String : Any], context: nil).size.height <= labelHeight
return prev
}
return self.text!.characters.count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment