Using a XIB file for custom Tableview Section Header

后端 未结 3 1972
余生分开走
余生分开走 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:48

    Try this: I have tested it in my app and its working:

    NSArray *viewArray =  [[NSBundle mainBundle] loadNibNamed:@"SectionHeaderview" owner:self options:nil];  
    UIView *view = [viewArray objectAtIndex:0]; 
    UILabel *lblTitle = [view viewWithTag:101]; 
    lblTitle.text = @"Text you want to set"; 
    return view;
    
    0 讨论(0)
  • 2021-02-15 15:51

    You can solve this issue by one of the following way:

    1) you have derived SectionHeaderView from UIView. derive this class with UIViewController instead. This will resolve your issue.

    2) Instead of using IBOutlet property, Set Tag of UILabel in view (say 101).

    Discard SectionHeaderview class.

    Keep SectionHeaderView.XIB, delete .m and .h files only.

    use following code ins Viewforheader method of MasterViewController class:

    {
        UIViewController *vc=[[UIViewController alloc] initWithNibName:@"SectionHeaderview" bundle:nil]
    
        UILable *lblTitle =[vc.view viewWithTag:101];
    
        lblTitle.text =@"Text you want to set";
    
        return vc.view;
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题