Here is a subclass of UILabel that will do what you want. Notice, I went to zero to optimize this. This part is up to you. My general recommendation, in terms of accessibility, would still be to just leave it. Overriding the accessibility label to display only part of the text in the actual label is a very dubious task from the point of view of A11y. Use this tool very carefully!
@interface CMPreivewLabel : UILabel
@end
@implementation CMPreviewLabel
- (NSString*)accessibilityLabel {
return [self stringThatFits];
}
- (NSString*)stringThatFits {
if (self.numberOfLines != 1) return @"This class would need modifications to support more than one line previews";
const int width = self.bounds.size.width;
NSMutableAttributedString* resultString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
while (width < resultString.size.width) {
NSRange range = [resultString.string rangeOfString:@" " options:NSBackwardsSearch];
range.length = resultString.length - range.location;
[resultString.mutableString replaceCharactersInRange:range withString:@""];
}
return resultString.string;
}
@end
source
share