AutoLayout 和 UILabel 不兼容






4.92/5 (4投票s)
这个实用技巧是 iOS 6 和 7 中一个缺陷的简单解决方法。
问题
AutoLayout 约束对于页面布局来说是一个巨大的改进,但它并不总是像预期的那样工作。以 UILabel
为例。当约束到另一个控件,并且行数设置为 0
时,文本应该由于 UILabel
的约束而被强制换行。不幸的是,你得到的结果看起来像这样。对 UILabel
的约束被忽略了。
解决方案
幸运的是,有一个简单的解决方法,这里用 C# (针对 Xamarin.iOS) 演示。
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
}
}
通过继承 UIView
并重写 LayoutSubviews
,我们可以将 PreferredMaxLayoutWidth
设置为控件父视图的宽度,从而得到预期的结果。
只需在 UILabel
的位置使用新的类即可。
历史
- 2013 年 12 月 9 日:首次发布。