gpt4 book ai didi

c# - 如何在约束条件下使多个按钮居中?

转载 作者:行者123 更新时间:2023-11-29 11:25:10 25 4
gpt4 key购买 nike

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

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

最佳答案

我写了一个简单的 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);
}

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

关于c# - 如何在约束条件下使多个按钮居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com