How do you return a multiline text CGSize from the new iOS 7 method sizeWithAttributes?
I would like this to produce the same results as sizeWithFont:constrainedToSi
CGSize stringsize = [lbl.text sizeWithAttributes:
@{NSFontAttributeName:[UIFont fontWithName:FontProximaNovaRegular size:12.0]}];
CGSize adjustedSize = CGSizeMake(ceilf(stringsize.width), ceilf(stringsize.height));
use ceilf
method to manage properlly
If you have the text, font, numberOfLines and width of your label set, this method returns the size of your label:
myLabel.numberOfLines = 0;
CGSize size = [myLabel sizeThatFits:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)];`
[As a new user, I cannot post a comment to @testing's answer, but to make his answer (for xamarin.ios) more useful]
We can return a CGRect and only use the height parameter for the gui item we are targeting UIButton etc.Passing in any parameters we need as below
public CGRect GetRectForString(String strMeasure, int fontSize, nfloat guiItemWidth)
{
UIFont descriptionLabelFont = UIFont.SystemFontOfSize (fontSize);
NSString textToMeasure = (NSString)strMeasure;
CGRect labelRect = textToMeasure.GetBoundingRect (
new CGSize(guiItemWidth, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes () { Font = descriptionLabelFont },
new NSStringDrawingContext ()
);
return labelRect;
}
header_Revision.Frame = new CGRect (5
, verticalAdjust
, View.Frame.Width-10
, GetRectForString( header_Revision.Title(UIControlState.Normal)
, 18
, View.Frame.Width-10 ).Height
);
For Xamarin.iOS:
UIFont descriptionLabelFont = UIFont.SystemFontOfSize (11);
NSString textToMeasure = (NSString)DescriptionLabel.Text;
CGRect labelRect = textToMeasure.GetBoundingRect (
new CGSize(this.Frame.Width, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes () { Font = descriptionLabelFont },
new NSStringDrawingContext ()
);
This is how I did it:
// Get a font to draw it in
UIFont *font = [UIFont boldSystemFontOfSize: 28];
CGRect textRect;
NSDictionary *attributes = @{NSFontAttributeName: font};
// How big is this string when drawn in this font?
textRect.size = [text sizeWithAttributes:attributes];
// Draw the string
[text drawInRect:textRect withAttributes:attributes];
Swift 2.3:
let attributes = [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 14)]
let rect = NSString(string: textToMeasure).boundingRectWithSize(
CGSizeMake(width, CGFLOAT_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: attributes, context: nil)
Swift 4:
let attributes = [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 14)]
let rect = NSString(string: textToMeasure).boundingRect(
with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: attributes as [NSAttributedString.Key : Any], context: nil)