ストーリーボードを使用してカスタムテーブルビューセクションのヘッダーとフッターを実装する方法 質問する

ストーリーボードを使用してカスタムテーブルビューセクションのヘッダーとフッターを実装する方法 質問する

ストーリーボードを使用せずに、 をUIViewキャンバスにドラッグしてレイアウトし、 またはデリゲート メソッドで設定するだけtableView:viewForHeaderInSectionですtableView:viewForFooterInSection

UIViewをキャンバスにドラッグできないStoryBoardでこれを実現するにはどうすればよいでしょうか

ベストアンサー1

セクション ヘッダーおよび/またはフッターとしてプロトタイプ セルを使用します。

  • 追加のセルを追加し、その中に必要な要素を配置します。
  • 識別子を特定のものに設定する(私の場合はSectionHeader)
  • tableView:viewForHeaderInSection:メソッドまたはtableView:viewForFooterInSection:メソッドを実装する
  • [tableView dequeueReusableCellWithIdentifier:]ヘッダーを取得するために使用する
  • メソッドを実装しますtableView:heightForHeaderInSection:

(スクリーンショットを参照)

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *CellIdentifier = @"SectionHeader"; 
    UITableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (headerView == nil){
        [NSException raise:@"headerView == nil.." format:@"No cells with matching CellIdentifier loaded from your storyboard"];
    }
    return headerView;
}  

編集:ヘッダータイトルを変更する方法(コメント付きの質問):

  1. ヘッダーセルにラベルを追加する
  2. ラベルのタグを特定の番号に設定する(例:123)
  3. メソッド内で、tableView:viewForHeaderInSection:次の呼び出しによってラベルを取得します。
    UILabel *label = (UILabel *)[headerView viewWithTag:123]; 
  1. これで、ラベルを使用して新しいタイトルを設定できます。
    [label setText:@"New Title"];

おすすめ記事