How to mimic UITableView's UITableViewStylePlain section header style

前端 未结 4 1683
孤街浪徒
孤街浪徒 2020-12-25 09:18

My application uses abbreviations in UITableView section header titles that are hard for VoiceOver to pronounce. As I need to make these titles pronounceable by

4条回答
  •  萌比男神i
    2020-12-25 09:47

    I found that the other answers either don't work or don't mimic the standard look. Here's mine, which works for iOS 5 and 6.

    Note that if you're on iOS 6, you should use dequeueReusableHeaderFooterViewWithIdentifier, which makes things much easier and cleaner.

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        if ([tableView respondsToSelector:@selector(dequeueReusableHeaderFooterViewWithIdentifier:)]) 
        {
            static NSString *headerReuseIdentifier = @"TableViewSectionHeaderViewIdentifier";
            UITableViewHeaderFooterView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerReuseIdentifier];
            if(sectionHeaderView == nil){
                sectionHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerReuseIdentifier];
            }
    
            //customise the label here:
            //[sectionHeaderView.textLabel setTextColor:[UIColor whiteColor]];
    
            return sectionHeaderView;
        }
        else 
        {            
            UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44.0)];
    
            UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 10, 290, 0)];
            headerLabel.backgroundColor = [UIColor clearColor];
            headerLabel.text = [self tableView:tableView titleForHeaderInSection:section];
            headerLabel.font = [UIFont boldSystemFontOfSize:17];
            headerLabel.textAlignment = NSTextAlignmentLeft;
            headerLabel.shadowColor = [UIColor clearColor];
            headerLabel.numberOfLines = 0;
            [headerLabel sizeToFit];
            [headerView setFrame:CGRectMake(headerView.frame.origin.x, headerView.frame.origin.y, headerView.frame.size.width, headerLabel.bounds.size.height)];
    
            //some customisation:
            headerLabel.textColor = [UIColor whiteColor];
    
            [headerView addSubview: headerLabel];
    
            return headerView;
        }
    }
    

    As the docs say, if you implement viewForHeaderInSection you must also implement heightForHeaderInSection. Implement it like this to make sure that it gets the right size for any number of lines:

    -(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        return UITableViewAutomaticDimension;
    }
    

提交回复
热议问题