Click here to Skip to main content
15,880,469 members
Articles / Mobile Apps / Xamarin
Tip/Trick

AutoLayout and UILabel Don't Get Along

Rate me:
Please Sign up or sign in to vote.
4.92/5 (4 votes)
12 Dec 2013CPOL 12K   3  
This handy tip is an easy workaround for a shortcoming in iOS 6 and 7.

Problem

AutoLayout constraints are a huge improvement for page layout, but it doesn't always act the way it should. Take the UILabel for example. When constrained to another control, and the number of lines is set to 0, the text should be forced to wrap due to the UILabel's constraints. Unfortunately what you get looks like this. The constraint on the UILabel is ignored.

Solution

Luckily there is a simple workaround, shown here in C# (for Xamarin.iOS).

C#
using MonoTouch.UIKit;

namespace RedCell.UI.Controls
{
    /// <summary>
    /// A workaround to allow wrapping with Auto Layout.
    /// </summary>
    internal class CustomUILabel : UILabel
    {
        #region Overrides of UIView
        /// <summary>
        /// Lays out subviews.
        /// </summary>
        public override void LayoutSubviews ()
        {
            base.LayoutSubviews();
            this.PreferredMaxLayoutWidth = this.Superview.Bounds.Size.Width;
        }
        #endregion
    }
}

Subclassing UIView and overriding LayoutSubviews, we can set PreferredMaxLayoutWidth to the width of the control's parent, resulting the expected result:

Simply use the new class in place of UILabel.

History

  • December 9, 2013: Initial publication.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Robotic Assistance Devices / AITX
Canada Canada
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Concept Designer at Robotic Assistance Devices

He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).

Yvan draws on experience as owner of Red Cell Innovation Inc., Mabel's Labels Inc. as Manager of Systems and Development, the University of Waterloo as Information Systems Manager, and OTTO Motors as Senior Systems Engineer and Senior Concept Designer.

Yvan is currently focused on design of embedded systems.

Comments and Discussions

 
-- There are no messages in this forum --