2

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.

Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70

2 Answers2

2

Alternatively, you could also use the textLabel property of UITableViewHeaderFooterView.

Code example:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UITableViewHeaderFooterView *headerView = [[UITableViewHeaderFooterView alloc] init];
    headerView.textLabel.text = @"tableview header";
    headerView.isAccessibilityElement = YES;
    headerView.accessibilityLabel = @"tableview header for accessibility";

    return headerView;
}
Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70
1

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.

XLE_22
  • 5,124
  • 3
  • 21
  • 72