Skip to content

Instantly share code, notes, and snippets.

@benhenderson
Created December 4, 2013 22:02
Show Gist options
  • Select an option

  • Save benhenderson/7796404 to your computer and use it in GitHub Desktop.

Select an option

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.
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