简体   繁体   中英

Programmatically add UITextField to UIView with MonoTouch

I am learning to use MonoTouch. I have a screen with two buttons. When a user clicks a button, a view that I have programmatically created will appear and hide the other. I have this successfully working. In one of my views, I want to show a text box. While I believe that I have created / add the the text box correctly to my view, it is not appearing. My initialization code is shown here:

RectangleF rectangle1 = new RectangleF(0, 100, 200, 200);
this.view1 = new UIView(rectangle1);
this.View.Add(view1);

RectangleF rectangle2 = new RectangleF(0, 0, UIScreen.MainScreen.Bounds.Width, 300);
this.view2 = new UIView(rectangle2);
this.view2.Hidden = true;
this.view2.BackgroundColor = UIColor.Green;

UITextField textField = new UITextField();
textField.Bounds = new RectangleF(20, 13, 200, 31);
view2.AddSubView(textField);

this.View.Add(view2);

What am I doing wrong? Why isn't the textField appearing?

Thank you!

Replace

textField.Bounds = new RectangleF(20, 13, 200, 31);

with

textField.Frame = new RectangleF(20, 13, 200, 31);

Your textField is a subview of View2 . Since you are setting view2.Hidden = true , it is also hiding ALL of the subviews of View2, which includes the text field.

Another thing you need to watch out for is what view is "on-top". Try playing around with the SendSubviewToBack(UIView view) and BringSubviewToFront(UIView view) methods of UIView.

Have you tried removing and or changing the order of how you add the view I believe all you need is

this.view2.AddSubView(textField);
or     
this.View.AddSubview(view2); 

It's probably because you mark view2 as hidden. Therefore, the entire view isn't even visible. If you remove the this.view2.Hidden = true you should see your text field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM