2016-07-22 177 views
1

我想動態生成幾個按鈕,數字將由背景給出。當我得到它時,我必須用它來創建相應的數字按鈕,每個按鈕的大小相同,並且它們之間的空間相同,如果按鈕不能包含在一行中,它將換行。最小寬度將是一個常量,但實際長度將按照按鈕的標題文本。 我的代碼在下面,但它不能換行,也不知道如何使用文本來確定按鈕的長度,感激任何指導。動態生成按鈕

- (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]; 
    } 
} 
+0

是你正在尋找一個「的網格按鈕」搜索。 – vikingosegundo

回答

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