2014-11-29 4 views
0

동적으로 버튼 행이있는 테이블을 채우려고합니다. 테이블이 시작되면 올바른 버튼을 포함하는 배열을 전달합니다. 버튼의 수와 행은 다양합니다. 첫 번째 행에 너무 많은 버튼을 삽입 할 때까지 새로운 행을 만들어야합니다. 행 당 4 개의 버튼으로 제한한다고 가정 해 보겠습니다. 그런 다음 내 버튼은 행 2에서 시작하고 행 1에서 시작하지 않아야합니다. 그들은 또한 오른쪽 경계에서 잘립니다. 난 그냥 오른쪽에있는 버튼을 계속 추가 할을 말하고 실현 enter image description here적절한 테이블 행에 버튼 배열 추가

좋은 - 나쁜 enter image description here

예 버튼이 1 행에 맞게 - 1 개 행을 초과

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSInteger rows = 0; // No rows if section is unknown! 
    switch (section) 
    { 
     case TableViewSectionFormatButtons: 
     { 
      if ([[self fileTypeButtonsArray] count] % kButtonsPerRow) 
       return ([[self fileTypeButtonsArray] count]/kButtonsPerRow) + 1; 
      else 
       return [[self fileTypeButtonsArray] count]/kButtonsPerRow; 
     } 
      break; 
     case TableViewSectionExportSwitches: 
      rows = 4; 
      break; 
     case TableViewSectionExportButton: 
      rows = 1; 
      break; 
     default: 
      break; 
    } 

    return rows; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *defaultCellIdentifier = @"defaultCellIdentifier"; 
    static NSString *detailCellIdentifier = @"detailCellIdentifier"; 

    UITableViewCell *cellToReturn = nil; 

    // Usage note: Both kinds of cells get created every time, which is arguably wasteful. Since there aren't many rows involved 
    // it's simpler just to ignore the one that we don't need. Assign the one we want to cellToReturn. 

    UITableViewCell *defaultCell = [tableView dequeueReusableCellWithIdentifier:defaultCellIdentifier]; // Image on left 
    if (defaultCell == nil) { 
     defaultCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:defaultCellIdentifier]; 
    } 

    UITableViewCell *detailCell = [tableView dequeueReusableCellWithIdentifier:detailCellIdentifier]; // Text on right 
    if (detailCell == nil) { 
     detailCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:detailCellIdentifier]; 
    } 

    // Clear old values 
    defaultCell.textLabel.textAlignment = NSTextAlignmentLeft; 
    defaultCell.accessoryType = UITableViewCellAccessoryNone; 
    defaultCell.accessoryView = nil; 
    defaultCell.imageView.image = nil; 

    detailCell.accessoryType = UITableViewCellAccessoryNone; 
    detailCell.imageView.image = nil; 


    switch (indexPath.section) { 
     case TableViewSectionFormatButtons: { 

      for (int i = 0; i < [self.fileTypeButtonsArray count]; i++) 
      { 
       UIButton *currentButton = (UIButton *)[self.fileTypeButtonsArray objectAtIndex:i]; 
       [currentButton setTag:i]; 

       [currentButton setFrame:CGRectMake((kButtonPadding + (i * (kButtonWidth + kButtonPadding))), kButtonPadding, kButtonWidth, kButtonHeight)]; 
       [defaultCell.contentView addSubview:currentButton]; 
      } 

      defaultCell.selectionStyle = UITableViewCellSelectionStyleNone; 



      cellToReturn = defaultCell; 
     } 
      break; 

     case TableViewSectionExportSwitches: { 

      defaultCell.selectionStyle = UITableViewCellSelectionStyleNone; 

      if (indexPath.row == 0) { 
       defaultCell.textLabel.text = NSLocalizedString(@"synopsisSwitchLabel", @"Synopsis - Export switch label to indicate if Synopsis text should be included in export."); 
       self.synopsisSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
       defaultCell.accessoryView = self.synopsisSwitch; 
//    self.synopsisSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsShowNotesIndicatorKey]; 

       [self.synopsisSwitch addTarget:self action:@selector(synopsisSwitchValueChanged:) forControlEvents: UIControlEventValueChanged]; 

      } 

      else if (indexPath.row == 1) 
      { 
       defaultCell.textLabel.text = NSLocalizedString(@"bodySwitchLabel", @"Body - Export switch label to indicate if Body text should be included in export."); 
       self.bodySwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
       defaultCell.accessoryView = self.bodySwitch; 

//    self.bodySwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsShowNotesIndicatorKey]; 
       [self.bodySwitch addTarget:self action:@selector(bodySwitchValueChanged:) forControlEvents: UIControlEventValueChanged]; 
      } 

      else if (indexPath.row == 2) 
      { 
       defaultCell.textLabel.text = NSLocalizedString(@"notesSwitchLabel", @"Notes - Export switch label to indicate if Notes should be included in export."); 

      self.notesSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
       defaultCell.accessoryView = self.notesSwitch; 

//    self.notesSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsShowExpandedOutlineKey]; 
       [self.notesSwitch addTarget:self action:@selector(notesSwitchValueChanged:) forControlEvents: UIControlEventValueChanged]; 
      } 

      else if (indexPath.row == 3) 
      { 
       defaultCell.textLabel.text = NSLocalizedString(@"imagesSwitchLabel", @"Images - Export switch label to indicate if Images should be included in export."); 
       self.imagesSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
       defaultCell.accessoryView = self.imagesSwitch; 

//    self.imagesSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsStoryboardModeKey]; 
       [self.imagesSwitch addTarget:self action:@selector(imagesSwitchValueChanged:) forControlEvents: UIControlEventValueChanged]; 
      } 

      cellToReturn = defaultCell; 
     } 
      break; 

     case TableViewSectionExportButton: 
     { 
      defaultCell.textLabel.textAlignment = NSTextAlignmentCenter; 
      if (indexPath.row == 0) 
      { 
       defaultCell.textLabel.text = NSLocalizedString(@"nextButtonTitle", @"Next - Button title indicating user is ready to proceed with Export."); 
       defaultCell.textLabel.textColor = [UIColor blueColor]; 
      } 

      cellToReturn = defaultCell; 
     } 
      break; 

    } 

    return cellToReturn; 
} 

예 버튼 서로. 나는 그것들을 넣을 행을 어떻게 말하는지 잘 모르겠다. 또한 맨 위의 행 (색인 0) 대신에 두 번째 행 (색인 1)에서 시작하는 이유를 왜곡했다. 도움을 주셔서 감사합니다.

+0

을 포함하는 질문을 편집 할 수 전체 cellForRowAtIndexPath 메소드? –

+0

물론입니다. 관련성이없는 물건들로 상당히 큽니다.하지만 도움이된다면 ... – DenVog

답변

1

TableViewSectionFormatButtons:TableViewSectionFormatButtons: 방법은 버튼이 행에 잘 맞으면 추가 행을 추가합니다 (즉, if ([[self fileTypeButtonsArray] count] % kButtonsPerRow)). 그러나 이것은 당신이하고 싶은 것과는 정반대로 들립니다.

case TableViewSectionFormatButtons: { 
    return ([[self fileTypeButtonsArray] count] + kButtonsPerRow - 1)/kButtonsPerRow; 
} 

에 : 당신은 단지 당신이 위의 행에 깔끔하게 맞지 않을 수있는 버튼,이 경우, 내가 대신 한 줄에 이렇게 제안이있는 경우 별도의 행에 압정하려는 것처럼 소리 단순히 정수 나누기를 반올림합니다.

cellForRowAtIndexPath: 메서드의 경우, (1) 알고리즘 당 kButtonsPerRow이되어야합니다. (2) 추가 할 행을 알아야합니다.) 그 정보를 사용하여 현재 행의 현재 행에 속하는 버튼 만 넣으면됩니다. 따라서 해당 루프가 0에서 시작하여 버튼 배열의 끝까지 가도록하지 마십시오. 예 :

case TableViewSectionFormatButtons: { 

    // Calculate the index of the first button in the current row 
    int firstButtonIndex = indexPath.row * kButtonsPerRow; 

    // Then starting from that index place kButtonsPerRow within that row 
    for (int i = firstButtonIndex ; i < firstButtonIndex + kButtonsPerRow ; i++) { 

     if (self.fileTypeButtonsArray.count > i) { 
      UIButton *currentButton = (UIButton *)[self.fileTypeButtonsArray objectAtIndex:i]; 
      [currentButton setTag:i]; 
      [currentButton setFrame:CGRectMake((kButtonPadding + ((i-firstButtonIndex) * (kButtonWidth + kButtonPadding))), kButtonPadding, kButtonWidth, kButtonHeight)]; 
      [defaultCell.contentView addSubview:currentButton]; 
     } 
    } 

    defaultCell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cellToReturn = defaultCell; 
} 

이와 비슷한 것이 좋습니다.

P. 각각의 cellForRowAtIndexPath: 동안 셀을 재사용하고 단추를 하위보기로 추가한다는 사실은 앞으로 몇 가지 문제를 일으킬 것입니다. 당신은, 당신은 이미 당신의 코드에서 수행 한 방법으로 이전 값을 지우려고하는 경우에 아마 당신은 또한 같은 장소, 예 오래된 버튼을 제거해야합니다 :

// Clear old values 
defaultCell.textLabel.textAlignment = NSTextAlignmentLeft; 
defaultCell.accessoryType = UITableViewCellAccessoryNone; 
defaultCell.accessoryView = nil; 
defaultCell.imageView.image = nil; 

for (UIView *view in [defaultCell subviews]) { 
    if ([view isKindOfClass:[UIButton class]]) { 
     [view removeFromSuperview]; 
    } 
} 
+0

사려 깊고 자세한 답장을 보내 주셔서 감사합니다. numberOfRowsInSection과 관련하여 절대적으로 맞습니다. 그것은 나에게 원하는 결과를 주었지만 옳은 이유는 아닙니다. – DenVog

+0

버튼 수가 행당 허용되는 버튼보다 큰 배열을 전달하면 cellForRowAtIndexPath가 충돌합니다. 'NSRangeException'이라는 캐치되지 않은 예외로 인해 앱이 종료됩니다. 이유는 다음과 같습니다. '*** - [NSArrayM objectAtIndex :] : 인덱스 5가 경계를 넘었습니다 [0 .. 4]. 이 문제는이 줄 거짓말을 믿습니다 : for (int i = firstButtonIndex; i DenVog

+0

@DenVog 네, 맞습니다. 이 경우를 포함하도록 답변을 업데이트하겠습니다. –

관련 문제