【问题标题】:Howto layout Custom iOS View (UIStackView / UILabel) in Xamarin Forms如何在 Xamarin 表单中布局自定义 iOS 视图(UIStackView / UILabel)
【发布时间】:2018-03-16 14:52:45
【问题描述】:

我一直在尝试在 Xamarin 表单中实现自定义复选框渲染器 + 视图。

iOS 上,我在布局自定义复选框和多行标签时遇到了问题;据说是因为我为视图设置了一个固定的框架。
但是,如果不设置 Frame,则什么都不会显示。


多行标签被截断(见复选框2):

这里我增加了 UIStackView 的 Frame 高度,
标签的内容现在完全显示:


这是我当前的实现:

public sealed class CheckboxView : UIStackView
{

    ...

    private void Setup()
    {
        //
        // Configure the StackView
        //

        Alignment = UIStackViewAlignment.Fill;
        Distribution = UIStackViewDistribution.FillProportionally;
        Axis = UILayoutConstraintAxis.Horizontal;
        Spacing = 15;

        Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 20);

        //
        // Image + Image Holder View (checkbox)
        //

        imageView = new UIImageView();
        imageView.Frame = new CGRect(x: 0, y: 0, width: 20, height: 20);
        imageView.Image = UIImage.FromFile("checkbox-checked.png");

        var imageHolderView = new UIView();
        imageHolderView.WidthAnchor.ConstraintEqualTo(20).Active = true;
        imageHolderView.TranslatesAutoresizingMaskIntoConstraints = false;
        imageHolderView.BackgroundColor = UIColor.Red;

        imageHolderView.AddSubview(imageView);
        AddArrangedSubview(imageHolderView);

        //
        // Label
        //

        label = new UILabel();
        AddArrangedSubview(label);

        label.Text = text;
        label.Lines = 0;
        label.LineBreakMode = UILineBreakMode.WordWrap;
        label.Font = UIFont.PreferredCaption1;
        label.BackgroundColor = UIColor.Yellow;
    }

    ...

}

除了设置 Frame 之外,我还尝试使用 Auto-Layout 锚点将 StackView 的顶部、左侧和右侧固定到 Superview,不幸的是没有取得多大成功。

是否有一种简单的解决方案可以使 StackView 自动扩展到所包含 UILabel 的假定高度?

任何帮助将不胜感激。
谢谢。

【问题讨论】:

    标签: ios xamarin xamarin.forms xamarin.ios autolayout


    【解决方案1】:

    Horizontal UIStackView 如果您使用 AutoLayout,将自动调整其高度。但是您应该添加正确的Constraints。我使用您的代码创建具有以下约束的自定义控件,它可以正常工作:

    var check = new CheckboxView();
    //Set this to enable AutoLayout
    check.TranslatesAutoresizingMaskIntoConstraints = false;
    View.AddSubview(check);
    
    check.TopAnchor.ConstraintEqualTo(TopLayoutGuide.GetBottomAnchor()).Active = true;
    //Set some long string
    check.labelText = "some string...";
    check.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor).Active = true;
    check.WidthAnchor.ConstraintEqualTo(120).Active = true;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多