开发者社区> 问答> 正文

如何用约束使多个按钮居中?

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

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

展开
收起
游客5akardh5cojhg 2019-12-11 22:11:21 414 0
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);
    }
    
    

    如果你有什么问题可以问我。

    2019-12-11 22:11:57
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多