Skip to content

Instantly share code, notes, and snippets.

@ozzieperez
Created June 26, 2015 20:48
Show Gist options
  • Save ozzieperez/7a2258c258f55c4999de to your computer and use it in GitHub Desktop.
Save ozzieperez/7a2258c258f55c4999de to your computer and use it in GitHub Desktop.
Xamarin IOS - Get the size of a string
//Method 1: No restrictions
((NSString)t.Text).GetSizeUsingAttributes(new UIStringAttributes {Font = t.Font});
//Method 2: Has to fit within a width
label.Frame = new CGRect(CGPoint.Empty, ((NSString)label.Text).GetBoundingRect(
new CGSize(width, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes { Font = label.Font},
null
).Size);
//Method 3: Has to fit within a width (Deprecated)
label.Frame = new CGRect(new CGPoint(0, 0), label.Text.StringSize(label.Font, width, UILineBreakMode.WordWrap));
//Method 4: Get the height of a string
var height = NSString(myText).GetBoundingRect(new CGSize(tableView.Frame.Width, nfloat.MaxValue),
NSStringDrawingOptions.UsesLineFragmentOrigin,
new UIStringAttributes { Font = UIFont.SystemFontOfSize(15) }, null).Height;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment