gpt4 book ai didi

ios - 基于CGSIZE的NSString字符串

转载 作者:行者123 更新时间:2023-12-01 16:33:54 27 4
gpt4 key购买 nike

我的NSString长,只想获取适合CGSize的字符串。

例:

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

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

请忽略语法。

从上面的详细信息中,我可以得到适合NSSize的CGSize并得到省略号。

下面的问题仅返回大小/宽度:
iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize

最佳答案

我刚刚在最近的项目中将其作为NSString上的类别实现,似乎运行良好。它当前可以与宽度一起使用,但是您也应该能够使其适应高度。

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

关于ios - 基于CGSIZE的NSString字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926465/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com