Search code examples
iosobjective-cuitableviewuiaccessibility

Setting accessibilityLabel for UITableView header text


I am trying to find a way to set accessibilityLabel for my tableview's header text.

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {        
    return @"Table View Header";
}

In my case, my accessibility label is different from the returned tableview's header text.


Solution

  • To set the accessibilityLabel property, write the text in the definition of the header view itself as I did in the code snippet hereunder by adding an accessibility element:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
        CGRect headerViewFrame = CGRectMake(0.0, 0.0, tableView.frame.size.width, 44.0);
        UIView * headerView = [[UIView alloc] initWithFrame:headerViewFrame];
    
        UILabel * headerViewLabel = [[UILabel alloc] initWithFrame:headerViewFrame];
        headerViewLabel.text = @"Table View Header";
        [headerView addSubview: headerViewLabel];
    
        UIAccessibilityElement * a11yHeader = [[UIAccessibilityElement alloc] initWithAccessibilityContainer:headerView];
        a11yHeader.accessibilityFrameInContainerSpace = headerView.frame;
        a11yHeader.isAccessibilityElement = YES;
        a11yHeader.accessibilityLabel = @"my new header text for accessibility";
        a11yHeader.accessibilityTraits = UIAccessibilityTraitHeader;
    
        headerView.accessibilityElements = @[a11yHeader];
    
        return headerView;
    }
    

    Try this out and adapt it to your application.

    Not that easy to go back to ObjC 🤯 but, now, you can set accessibilityLabel for UITableView header text by following this rationale. 🎉🎊🥳