How do you make buttons programmatically using xamarin?

13,577

First create the button

UIButton button = new UIButton(); 
CGRect ScreenBounds = UIScreen.MainScreen.Bounds;
float buttonWidth = (float)ScreenBounds.X / 4;
button.Frame = new CGRect (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!");
};
Share:
13,577
parker88
Author by

parker88

Learning to code

Updated on June 04, 2022

Comments

  • parker88
    parker88 about 2 years

    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.