动态生成按钮

时间:2016-07-22 16:16:21

标签: ios objective-c uibutton

我想动态生成几个按钮,数字将由后台给出。当我得到它时,我必须使用它来创建相应的数字按钮,每个按钮将是相同的大小,它们之间的空间是相同的,如果按钮不能连续包含,它将换行。最小宽度将是常量,但实际长度将根据按钮的标题文本。 我的代码在下面,但它不能换行,我也不知道如何使用文本来确定按钮的长度,感谢任何指导。

- (void)viewDidLoad {   
    [super viewDidLoad];

    CGFloat testHeight = 50;
    CGFloat testWidth = 100;
    CGFloat spaceing = 10;
    int number = 5;

    for (int i = 0; i < number; i++) {   
        UIButton *button =  [[UIButton alloc]initWithFrame:CGRectMake(spaceing + testWidth * i + spaceing * i , 100 , testWidth, testHeight )];  
        [button setBackgroundColor:[UIColor redColor]];  
        [self.view addSubview:button];
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用UICollectionView来执行此操作,但仅使用UIButtons数组实现并不困难。您可以使用sizeToFit根据标题自定按钮大小。要让你的按钮换行,你应该检查它是否会超出你要添加它们的视图的最大x,在你的情况下self.view

例如,您可以说:

- (void)viewDidLoad {   
    [super viewDidLoad];
    NSArray *buttonStrings = @[@"how", @"now", @"brown", @"cow", @"the", @"quick", @"brown", @"fox"];
    NSMutableArray *buttons = [[NSMutableArray alloc]initWithCapacity:[buttonStrings count]];
    for (NSString *string in buttonStrings)
    {
        UIButton *button = [self buttonForString:string];
        [buttons addObject:button];
    }
    [self layoutButtonArray:buttons inView: self.view];
}
// takes an array of buttons and adds them as subviews of view
- (void)layoutButtonArray:(NSArray<UIButton *> *)buttons inView:(UIView *)view
{
    CGFloat spacing = 10.0;
    CGFloat xOffset = spacing;
    CGFloat yOffset = spacing;
    for (UIButton *button in buttons)
    {
        if((xOffset + button.bounds.size.width + spacing) > CGRectGetMaxX(view.bounds))
        {
            xOffset = spacing;
            yOffset += (button.bounds.size.height + spacing);
        }
        button.frame = CGRectMake(xOffset, yOffset, button.bounds.size.width, button.bounds.size.height);
        [view addSubview:button];
        xOffset += (button.bounds.size.width + spacing);
    }
}
// Takes a string returns a button sized to fit
- (UIButton *) buttonForString:(NSString *)string
{
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectZero];
    button.backgroundColor = [UIColor redColor];
    [button setTitle:string forState:UIControlStateNormal];
    [button sizeToFit];
    // if you want to have a minimum width you can add that here
    button.frame = CGRectMake(button.frame.origin.x, button.frame.origin.y, MAX(button.frame.size.width, kMinWidth), button.frame.size.height);
    return button;
}