NSString string based on CGSIZE

穿精又带淫゛_ 提交于 2019-12-11 04:37:00

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/29926465/nsstring-string-based-on-cgsize

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!