Avec ce code, vous pouvez changer la hauteur de vos UITextView en fonction d'une largeur fixe (il fonctionne sur iOS 7 et les versions antérieures) :
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
UITextView *textView = [[UITextView alloc] init];
[textView setAttributedText:text];
CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
Avec cette fonction, vous pourrez prendre un NSAttributedString et une largeur fixe pour revenir à la hauteur nécessaire.
Si vous voulez calculer l'image à partir d'un texte avec une police spécifique vous, plus besoin d'utiliser le code suivant :
- (CGSize)text:(NSString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
CGRect frame = [text boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName:font}
context:nil];
return frame.size;
}
else
{
return [text sizeWithFont:font constrainedToSize:size];
}
}
Vous pouvez ajouter qu' SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO
sur votre préfixe.pch fichier dans votre projet:
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
Vous pouvez également remplacer le test précédent) SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)
par :
if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])