Andrea Loda
Andrea Loda

Reputation: 71

Create button programmatically monotouch

Hi all i'm trying to create a button dynamically via code, but when i run the debugger the button isn't displayed in the simulator.

this is the code that i have written in the viewdidload metod

var button = UIButton.FromType(UIButtonType.RoundedRect);
            button.Frame = new System.Drawing.RectangleF(100f, 100f, 100f, 100f);
         button.SetTitle("click me", UIControlState.Normal);

i tried other code too for example :

UIButton button = new UIButton(UIButtonType.InfoDark); //BTN
button.Frame = new CoreGraphics.CGRect(59, 59, 59, 59);

i think that the problem is stupid but i can't find solution. thank you

Upvotes: 0

Views: 849

Answers (2)

Happiehappie
Happiehappie

Reputation: 1074

You allocated your button but you didn't add it to your view. Try this

self.view.addSubview(button)

In Xamarin, would be

this.AddSubview(button);

Upvotes: 0

SushiHangover
SushiHangover

Reputation: 74094

You have to Add it to your UIView (UIViewController)

UIButton button = new UIButton(UIButtonType.InfoDark); //BTN
button.Frame = new CoreGraphics.CGRect(59, 59, 59, 59);
Add(button);

Add

This is an alias for UIView.AddSubview, but uses the Add pattern as it allows C# 3.0 constructs to add subviews after creating the object.

Upvotes: 3

Related Questions