首页 > 解决方案 > Xamarin Forms如何在iOS上设置标签的最小宽度

问题描述

我正在尝试实现一些看起来很简单的事情:在 iOS 中使用自定义渲染器设置标签的最小宽度。到目前为止,我已经尝试过:


[assembly: ExportRenderer(typeof(CustomLabel), typeof(iOSLabelRenderer))]
namespace HopChild.CoreXamarin.iOS.Views
{
    public class iOSLabelRenderer : LabelRenderer
    {
        private float MinWidth => (float)((CustomLabel)this.Element).MinWidth;

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            this.SetMinWidth();
        }

        private void SetMinWidth()
        {
            this.TranslatesAutoresizingMaskIntoConstraints = false;

            // Tried this:
            this.WidthAnchor.ConstraintGreaterThanOrEqualTo(this.MinWidth).Active = true;

            // And this:
            this.Control.TranslatesAutoresizingMaskIntoConstraints = false;
            this.Control.WidthAnchor.ConstraintGreaterThanOrEqualTo(this.MinWidth).Active = true;

            // And this:
            var constraint = NSLayoutConstraint.Create(this.Control, NSLayoutAttribute.Width, NSLayoutRelation.GreaterThanOrEqual, 1, this.MinWidth);
            constraint.Active = true;
            this.Control.AddConstraint(constraint);
        }
    }
}

但无论我做什么,总会有另一个宽度约束在以后添加(基于我认为的标签内容),它推翻了我的约束。

任何想法?

标签: iosxamarin.forms

解决方案


推荐阅读