2013-10-09 47 views
0

我在桌面視圖中以編程方式添加了UITextView。我想爲它添加約束,所以它在縱向和橫向模式下看起來都是一樣的。我有以下代碼(C#,MonoTouch),但它不工作。 titleTxt是添加到單元格中的簡單文本字段。MonoTouch以編程方式向UITextField添加約束條件

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

而不是添加約束到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 }); 
+0

如果我們使用自動佈局和約束,我們是否真的需要給框架? – SARATH