我创造了六个按钮。但它们不是以屏幕为中心的。如何为这些按钮创建约束?
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);
}
如果你有什么问题可以问我。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。