我一直在尝试在 Xamarin Forms 中实现自定义复选框渲染器 + 视图。
在 iOS 上,我在布局自定义复选框与多行标签组合时遇到问题;据说是因为我正在为视图设置一个固定框架。
但是,如果不设置框架,则根本不会显示任何内容。
多行标签被切断(参见复选框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;
}
...
}
我没有设置框架,而是尝试使用自动布局锚点将 StackView 的顶部、左侧和右侧固定到超级视图,不幸的是没有取得太大成功。
是否有一个简单的解决方案可以使 StackView 自动扩展到所包含的 UILabel 的假定高度?
Horizontal UIStackView
将自动调整其高度。但您应该添加正确的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;