I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?
Thanks.
I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?
Thanks.
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;