How to get the width of an NSString?

Viewed 34136

I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?

Thanks.

12 Answers

This works with iOS 14.5

Objective-C

Define attributes:

 NSDictionary *attributes = @{
            NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:25],
            NSStrokeWidthAttributeName: @(0),
            NSStrokeColorAttributeName: [UIColor blackColor]
    };

Get width and height:

- (CGFloat)widthOfString:(NSString *)string {
    CGSize stringSize = [string sizeWithAttributes:attributes];
    return stringSize.width;
}

- (CGFloat)heightOfString:(NSString *)string {
    CGSize stringSize = [string sizeWithAttributes:attributes];
    return stringSize.height;
}

This will work. You can try it.

NSDictionary *attrDict = @{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
    lblDeliveryDateWidth = stringBoundingBox.width;
Related