向UIView添加按钮

时间:2014-08-14 15:48:05

标签: ios objective-c uiview

我想在UIView中添加按钮。按钮数量因视图而异。 我想实现以下目标:

Buttons in UIView

我尝试添加按钮(在foreach结构中),如下所示:

UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
but.frame= CGRectMake(200, 15, 15, 15);
[but setTitle:@"Ok" forState:UIControlStateNormal];
[but addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but];

但我不知道如何计算CGRectMake的新线。如何查看行尾(UIView)?或者添加像这样的按钮有点蠢?

由于 弗洛里安

2 个答案:

答案 0 :(得分:0)

设置标题后,需要添加计算按钮大小。然后跟踪前面按钮的当前X和Y,并确定新创建的按钮是否适合当前的“线”。否则转到下一个。

我建议您查看现有组件,看看他们是如何做到的,下面是几个链接。

https://github.com/domness/DWTagList

https://github.com/andreamazz/AMTagListView

答案 1 :(得分:0)

使用以下代码,您可以将多个按钮放在一行中,只要它们的总宽度和间隙小于视图的宽度。

 UIView *view = nil;
    NSArray *allBtns = nil;
    float viewWidth;

    float currentY = 0;
    float currentX = 0;
    float btnGapWidth = 10.0;
    float btnGapHeight = 2.0;
    for (UIButton *btn in allBtns) {
        CGRect rc = btn.frame;
        BOOL shouldAddToNewLine = viewWidth - currentX - btnGapWidth < rc.size.width ? YES : NO;

        if (shouldAddToNewLine) {
            rc.origin = CGPointMake(0, currentY + rc.size.height + btnGapHeight);
            currentX = 0;
            currentY += rc.size.height + btnGapHeight;
        } else {
            //another row
            rc.origin = CGPointMake(currentX + rc.size.width + btnGapWidth, currentY);
            currentX += rc.size.width + btnGapWidth;
        }
        btn.frame = rc;
        [view addSubview:btn];
    }