2013-03-29 2 views
1

У меня есть UIView, где я должен поместить несколько кнопок бок о бок в центре UIView, как показано на рисунке программнокак разместить кнопки бок о бок в UIView с выравниванием по центру

Подобно этому чертежу. кнопки должны быть размещены в центре UIView

-------------------------------- 
| ----  ----  ----  | 
|| | | | | |  | 
|| 1B | | 3B | | 5B |  | 
| ----  ----  ----  | 
| ----  ----     | 
|| 2B | | |     | 
|| | | 4B |     | 
| ----  ----     | 
-------------------------------- 
+1

вы можете реализовать свою собственную логику. – Balu

+0

Сколько кнопок вы хотели бы показать? и каждая строка содержит количество кнопок? –

ответ

1

Это то, что я выработал. Source Code

перечислимого типа для обозначения вы хотите vertial или горизонтально расположенные элементы

typedef enum { 
    ArrangementTypeHorz = 1, 
    ArrangementTypeVert = 2 
}ArrangementType; 

Заявленный номер или строк столбцов и тип расположения

@interface ATTViewController() 

{ 
    ArrangementType _arrangementType; 

    NSUInteger _rows; 
    NSUInteger _columns; 

} 

@end 

Метод вычисляет кадр индекса элемент WRT SuperView

- (CGRect)frameForItemAtIndex:(NSUInteger)index inSuperView:(UIView *)superView 
{ 
    CGFloat blockWidth = floorf(superView.frame.size.width/_columns); 
    CGFloat blockHeight = floorf(superView.frame.size.height/_rows); 

    NSUInteger row = 0; 
    NSUInteger column = 0; 

    if (_arrangementType == ArrangementTypeHorz) { 
     row = floorf((CGFloat)index/_columns); 
     column = index - row*_columns; 
    }else{ 
     column = floorf((CGFloat)index/_rows); 
     row = index - column*_rows; 
    } 

    CGFloat xOffset = 5.0f; 
    CGFloat yOffset = 5.0f; 

    return CGRectMake(blockWidth*column+xOffset, 
         blockHeight*row+yOffset, 
         blockWidth-(2*xOffset), 
         blockHeight-(2*yOffset)); 
} 

Добавление кнопок в кон, tainerView. При добавлении набора строк, столбцов и компоновки Type

- (void)addButtonsToContainerView 
{ 
    NSUInteger numberOfItems = 5; 

    _rows = 2; 
    _columns = 3; 

    _arrangementType = ArrangementTypeVert; 

    NSUInteger itemCount = 0; 

    while (itemCount<numberOfItems) 
    { 
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     CGRect frame = [self frameForItemAtIndex:itemCount inSuperView:self.containerView]; 
     [button setFrame:frame]; 
     NSString *title = [NSString stringWithFormat:@"Button %d",itemCount+1]; 
     [button setTitle:title forState:UIControlStateNormal]; 

     [self.containerView addSubview:button]; 

     itemCount ++; 
    } 
} 
1

Этот метод позволит создать 4 кнопки для каждой строки, так же, как в Фотогалерее IOS сделать необходимые изменения в Достичь в напечатанном

-(void)createButtons 
{ 
    int x, y, width, height, gapBetweenTwoButtons; 
    x = y = 4; 
    gapBetweenTwoButtons = 4; 
    int numberOfButtons = 10; 

    // i have calculated width for 4 columns it may vary for your requirement 
    width = height = 140; 

    // loop to create buttons 
    UIButton *btn; 

    for (int i=0; i< numberOfButtons; i++) 
    { 
     btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     [btn setFrame:CGRectMake(x, y, width/2, height/2)]; 

     // Add button to scrollview 
     [scrlViewSubCategory addSubview:btn]; 

     // calculate x and y accordingly 
     if((i+1) % 4 == 0) 
     { 
      x = gapBetweenTwoButtons; 
      y += (width/2)+gapBetweenTwoButtons; 
     } 
     else 
      x += (width/2)+gapBetweenTwoButtons; 
    } 

    // finally , adjust content size of scrollview 

    [scrlViewSubCategory setContentSize:CGSizeMake(scrlViewSubCategory.frame.size.width, (numberOfButtons/4) * ((width/2)+4))]; 
} 
0

Попробуйте это:

-(void) fillGridViewAfterCall 
    { 
      int count = [viewGrid.subviews count]; 
      for (int i = count-1; i >= 0; i--) 
      { 
        [[viewGrid.subviews objectAtIndex:i] removeFromSuperview]; 
      } 
      int videoCount = 0; 
      int posx = 10; 
      int posy = 10; 
      int mainLoopCount = ([arrUserVideos count]/3); 

      if (([arrUserVideos count]%3) > 0) 
      { 
        mainLoopCount = mainLoopCount + 1; 
      } 

      for (int i=0; i<mainLoopCount; i++) 
      { 
        posx = 10; 
        for (int j=0; j<3; j++) 
        { 
          VideoShare *shareObj = [arrUserVideos objectAtIndex:videoCount]; 

          UIButton *btnVideo = [[[UIButton alloc] init]; 
          btnVideo.frame = CGRectMake(posx, posy, 96, 96); 
          btnVideo.tag = shareObj.vdId; 
          btnVideo.layer.masksToBounds = YES; 
          btnVideo.layer.cornerRadius = 4.0; 
          [btnVideo setImage:[UIImage imageNamed:@"iconGridSelected.png"] forState:UIControlStateNormal]; 
          [btnVideo addTarget:self action:@selector(btnGridVideoClick:) forControlEvents:UIControlEventTouchUpInside]; 
          [viewGrid addSubview:btnVideo]; 
          videoCount++; 

          if (videoCount == [arrUserVideos count]) 
          { 
            break; 
          } 
          posx = posx + 102; 
        } 
        posy = posy + 102; 
      } 

      if (arrUserVideos.count == 0) 
      { 
        viewGrid.hidden = YES; 
      } 
      else 
      { 
        viewGrid.frame = CGRectMake(0, posyDynamic, 320, (posy+5)); 
        viewGrid.hidden = NO; 
      } 

      scrollObj.contentSize = CGSizeMake(320, (viewGrid.frame.size.height+100+scrollIncrement)); 
    } 
Смежные вопросы