Skip to content

Instantly share code, notes, and snippets.

@Shosta
Created August 7, 2013 14:54
Show Gist options
  • Save Shosta/6174758 to your computer and use it in GitHub Desktop.
Save Shosta/6174758 to your computer and use it in GitHub Desktop.
Calculate a Label size based on its content and a width. It is really useful when you wants to calculate a cell's height from its NSString label's content.
//--------------------------------------------------------
//
//--------------------------------------------------------
// Project :
// File : NSString+LabelSize.h
// Created : $ 11/06/12 $
// Maintainer : $ Rémi LAVEDRINE $
//
// Copyright Rémi LAVEDRINE 2004-2012, All Rights Reserved
//
// This software is the confidential and proprietary
// information of Rémi LAVEDRINE.
// You shall not disclose such Confidential Information
// and shall use it only in accordance with the terms
// of the license agreement you entered into with
// Rémi LAVEDRINE.
//--------------------------------------------------------
//
// @brief
// Calculate a Label size based on its content and a width.
// It is really useful when you wants to calculate a cell's height from its NSString label's content.
//
#import <Foundation/Foundation.h>
//! @brief Calculate a Label size based on its content and a width.
//! @class NSString+LabelSize
//! @ingroup Utilities
//! @author Rémi Lavedrine
@interface NSString (LabelSize)
- (CGFloat)getTextHeightAtFont:(UIFont*)font forWidth:(CGFloat)width;
@end
//
// NSString+LabelSize.m
//
//
// Created by Rémi LAVEDRINE on 11/06/12.
// Copyright (c) 2012 Rémi LAVEDRINE. All rights reserved.
//
#import "NSString+LabelSize.h"
@implementation NSString (LabelSize)
/**
@brief Get the height of a text based on its font.
@author : Rémi Lavedrine
@date : 11/06/2012
@remarks : <#(optional)#>
*/
- (CGFloat)getTextHeightAtFont:(UIFont*)font forWidth:(CGFloat)width{
CGSize size = CGSizeMake(width, 1000);// here is the trick.
CGSize textSize = [self sizeWithFont:font constrainedToSize:size];
return textSize.height;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment