【问题标题】:How to center multiple buttons with constraints?如何使多个带有约束的按钮居中?
【发布时间】:2019-12-11 13:51:06
【问题描述】:

我创建了六个按钮。但它们不在屏幕的中心。如何为这些按钮创建约束?

        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)
        }

【问题讨论】:

  • @jack-hua-msft 你能帮帮我吗
  • @Cheesebaron 你能帮帮我吗?
  • 你试过我的解决方案了吗?
  • @JackHua-MSFT 我需要你的帮助来解决这个问题:stackoverflow.com/questions/59621176/…

标签: c# ios xamarin


【解决方案1】:

我写了一个简单的addButtons 方法让你添加在屏幕上居中的按钮。

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);
}

如果您有任何问题,请随时问我。

【讨论】:

猜你喜欢
  • 2017-03-31
  • 2021-07-25
  • 2018-07-18
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多