0

我在 tableview 中以编程方式添加了 UITextView。我想为其添加约束,使其在纵向和横向模式下看起来相同。我有以下代码(C#,MonoTouch),但它不起作用。titleTxt 是添加到单元格的简单文本字段。

var rightSpaceConstraint = NSLayoutConstraint.Create (titleTxt, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, null, NSLayoutAttribute.Right, 1.0f, 20f);
var leftSpaceConstraint = NSLayoutConstraint.Create (titleTxt, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, null, NSLayoutAttribute.Left, 1.0f, 20f);

titleTxt.AddConstraints (new NSLayoutConstraint[] {rightSpaceConstraint, leftSpaceConstraint});

我应该如何添加约束来设置左右空格。

4

1 回答 1

1

您必须将约束添加到表格单元格,而不是向 titleTxt 添加约束。您还必须将 TranslatesAutoresizingMaskIntoConstraints 标志设置为 false。下面是可以正常工作的代码

        UILabel titleLbl = new UILabel ();
        titleLbl.Frame = new RectangleF (20,5,260,30);
        titleLbl.Text = "Please enter username";
        titleLbl.BackgroundColor = UIColor.Clear;
        titleLbl.Font = UIFont.SystemFontOfSize (13);
        titleLbl.TextAlignment = UITextAlignment.Center;

        titleLbl.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
        titleLbl.TranslatesAutoresizingMaskIntoConstraints = false;

        cell.ContentView.AddSubview (titleLbl);

        var titleLblRightSpaceConstraint = NSLayoutConstraint.Create (titleLbl, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, cell.ContentView, NSLayoutAttribute.Right, 1.0f, -20f);
        var titleLblLeftSpaceConstraint = NSLayoutConstraint.Create (titleLbl, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, cell.ContentView, NSLayoutAttribute.Left, 1.0f, 0f);

        cell.ContentView.AddConstraints (new NSLayoutConstraint[] {titleLblRightSpaceConstraint, titleLblLeftSpaceConstraint });
于 2013-10-10T20:47:25.500 回答