2

I have a long NSString and want to get only the string which gets fit in CGSize.

Example:

NSString *temp = @"jump jump jump jump jump jump";

CGSize = CGSizeMake(30,30);
UIFont *font = [UIFont fontwithName:@"helviticaNueue" fontSize:18];

Please ignore the syntax.

From above details can i get what NSString fits the CGSize and gets the ellipsis to.

Below question only return the size/width: iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize

Community
  • 1
  • 1
Arun Gupta
  • 2,628
  • 1
  • 20
  • 37
  • possible duplicate of [iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize](http://stackoverflow.com/questions/19145078/ios-7-sizewithattributes-replacement-for-sizewithfontconstrainedtosize) – Cameron Lowell Palmer Apr 28 '15 at 18:12
  • The possible duplicate does not return a truncated string, just a size. – picciano Apr 28 '15 at 18:16

2 Answers2

0

If your eventual aim is to put the string into a UILabel with a fixed width (and I'm making an assumption here), then just assign the NSString to the label and let UILabel handle the details (i.e., text alignment, baseline, line breaks, etc).

If not, then you will have to iterate over the string increasing it's length one character at a time and measure it using UIStringDrawing method:

- (CGSize)sizeWithAttributes:(NSDictionary *)attrs

And don't forget to measure the size of the ellipsis first and take that into account.

cbiggin
  • 1,942
  • 1
  • 17
  • 18
  • Sorry but i only need the string. If it would have been UILabel then i would have not even asked this question – Arun Gupta Apr 28 '15 at 18:06
0

I just implemented this as a category on NSString for a recent project, seems to be working fine. It currently works with width, but you should be able to adapt it to use height as well.

NSString-Truncate.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface NSString (Truncate)

- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes;

@end

NSString-Truncate.m

#import "NSString+Truncate.h"

@implementation NSString (Truncate)

- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes {
    CGSize size = [self sizeWithAttributes:textFontAttributes];
    if (size.width <= width) {
        return self;
    }

    for (int i = 2; i < self.length; i++) {
        NSString *testString = [NSString stringWithFormat:@"%@…", [self substringToIndex:self.length - i]];
        CGSize size = [testString sizeWithAttributes:textFontAttributes];
        if (size.width <= width) {
            return testString;
        }
    }
    return @"";
}

@end
picciano
  • 22,341
  • 9
  • 69
  • 82