Created
December 4, 2013 22:02
-
-
Save benhenderson/7796404 to your computer and use it in GitHub Desktop.
Extension for Xamarin.iOS that gives UILabel the ability resize its text to fit within its frame. Ported from this Stack Overflow answer: http://stackoverflow.com/a/15484031/1098404.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using MonoTouch.UIKit; | |
| using MonoTouch.Foundation; | |
| using System.Drawing; | |
| namespace Mapco.iOS | |
| { | |
| public static class UILabelExtension | |
| { | |
| public static void AdjustFontSizeToFit (this UILabel label) | |
| { | |
| var font = label.Font; | |
| var size = label.Frame.Size; | |
| for (var maxSize = label.Font.PointSize; maxSize >= label.MinimumScaleFactor * label.Font.PointSize; maxSize -= 1f) | |
| { | |
| font = font.WithSize (maxSize); | |
| var constraintSize = new SizeF (size.Width, float.MaxValue); | |
| var labelSize = (new NSString(label.Text)).StringSize(font, constraintSize, UILineBreakMode.WordWrap); | |
| if(labelSize.Height <= size.Height) { | |
| label.Font = font; | |
| label.SetNeedsLayout (); | |
| break; | |
| } | |
| } | |
| // set the font to the minimum size anyway | |
| label.Font = font; | |
| label.SetNeedsLayout (); | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment