Using a XIB file for custom Tableview Section Header

后端 未结 3 1965
余生分开走
余生分开走 2021-02-15 15:33

I wanted to use a xib file to customise a tableview section in xcode (objective C), and here ar my files:

SectionHeaderView.xib is a UIView with a UILabel

Sectio

3条回答
  •  迷失自我
    2021-02-15 15:52

    You can create a UITableViewCell subclass with an associated xib, and use it as the section header. In this example i will call it CustomTableViewHeaderCell.h/.m/.xib and show you how to change the text of a label inside this cell.

    • Create an outlet property in your CustomTableViewHeaderCell.h

      @property (weak, nonatomic) IBOutlet UILabel *sectionHeaderLabel;

    • Add a UITableViewCell into the empty CustomTableViewHeaderCell.xib and set the class of the element to CustomTableViewHeaderCell from the Identity Inspector.

    • Set also the Identifier (attribute inspector of the cell) for example CustomIdentifier.

    • Drag a label into the Content View and connect the outlet from the CustomTableViewHeaderCell (Not the file owner!).

    Then in each ViewController you want to use the table view section header cell:

    1) Register your xib to reuse identifier (probably in viewDidLoad):

    [_yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewHeader" bundle:nil] forCellReuseIdentifier:@"CustomIdentifier"];
    

    2) Override viewForHeaderInSection to display your custom cell header view

    -(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
        CustomTableViewHeaderCell * customHeaderCell = [tableView dequeueReusableCellWithIdentifier:@"CustomIdentifier"];
        customHeaderCell.sectionHeaderLabel = @"What you want";
        return customHeaderCell;
    }
    

提交回复
热议问题