MonoTouch以编程方式向UITextField添加约束

时间:2013-10-09 18:28:40

标签: ios6 xamarin.ios ios7

我在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});

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

1 个答案:

答案 0 :(得分: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 });