2016-07-22 3 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; 
} 
関連する問題