parker88 parker88 - 2 months ago 23x
C# Question

How do you make buttons programmatically using xamarin?

I'm trying to create buttons programmatically using the xamarin ide (c#). What code do I need to create the button, set its size, set its text, set its background color, and set its constraints? Is there a way to define the button as 1/4 of the width of the screen? Thanks in advance.


First create the button

UIButton button = new UIButton(); 
CGRect ScreenBounds = UIScreen.MainScreen.Bounds;
float buttonWidth = (float)ScreenBounds.X / 4;
button.Frame = new RectangleF (0f, 0f, buttonWidth, 50f); 
button.SetTitle ("Title", UIControlState.Normal);
button.BackgroundColor = UIColor.Green;

And then add it as a subview to the active view

this.AddSubview (button);

And to add event for TouchUpInside

button.TouchUpInside += (object sender, System.EventArgs e) => {
   Debug.WriteLine( "Button Clicked!");