简体   繁体   中英

How to center multiple buttons with constraints?

I created six buttons. But they are not centered on the screen. How can I create constraints for these buttons?

        var x = 50;
        var y = 50;
        var n=6
        int index = 0;
        while (index < n)
        {
            if (index % 3 == 0)
            {
                y += 70;
                x = 30;
            }
            UILabel btn = new UILabel(new CGRect(x, y, 90, 70));
            btn.BackgroundColor = UIColor.Red;
            btn.TextAlignment = UITextAlignment.Center;
            btn.Text = "botton" + index;
            x += 60;
            index++;
            this.View.add(btn)
        }

I wrote a simple addButtons method for you to add buttons which centered on the screen.

public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    // Perform any additional setup after loading the view, typically from a nib

    for (int i = 0; i < 6; i++)
    {
        addButtons(View,i);
    }
}

void addButtons(UIView backView, int buttonNumber) {

    //number of buttons in one line
    int cols = 3;

    //add it to buttonY to change the start position of Y
    var startYPadding = 30;

    var buttonWidth = 90;
    var buttonHeight = 70;

    var colMargin = (backView.Bounds.Size.Width - (cols * buttonWidth)) / (cols + 1);

    var col = buttonNumber % cols;
    var row = buttonNumber / cols;

    //if you want the paddings between buttons use below code
    //var buttonX = col * (buttonWidth + colMargin)+ colMargin;
    //var buttonY = row * (buttonHeight + colMargin) + startYPadding;

    //if you dont want the padding between buttons use below code
    var buttonX = (backView.Bounds.Size.Width - (cols * buttonWidth))/2 + col*buttonWidth;
    var buttonY = row * buttonHeight + startYPadding;

    UILabel btn = new UILabel(new CGRect(buttonX, buttonY, buttonWidth, buttonHeight));
    btn.BackgroundColor = UIColor.Red;
    btn.TextAlignment = UITextAlignment.Center;
    btn.Text = "botton" + buttonNumber;
    backView.Add(btn);
}

Feel free to ask me if you have any questions.

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