如何使用约束将多个按钮居中? [英] 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)
}
推荐答案
我写了一个简单的 addButtons
方法来让你添加以屏幕为中心的按钮.
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.
这篇关于如何使用约束将多个按钮居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文