Skip to content

Instantly share code, notes, and snippets.

@cscouto
Created August 20, 2018 18:29
Show Gist options
  • Save cscouto/0be954b3b9d3de33b0df80289f298513 to your computer and use it in GitHub Desktop.
Save cscouto/0be954b3b9d3de33b0df80289f298513 to your computer and use it in GitHub Desktop.
SWIFT - UILabel content size for specific width
//
// UILabel+height.swift
// AllBody
//
// Created by Tiago Do Couto on 8/20/18.
// Copyright © 2018 coutocode. All rights reserved.
//
import UIKit
extension UILabel {
func textHeight(withWidth width: CGFloat) -> CGFloat {
return text?.height(withWidth: width, font: font) ?? 0
}
}
extension String {
func height(withWidth width: CGFloat, font: UIFont) -> CGFloat {
let maxSize = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let contentSize = self.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin], attributes: [.font : font], context: nil)
return contentSize.height
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment