【问题标题】:NSString string based on CGSIZE基于 CGSIZE 的 NSString 字符串
【发布时间】:2015-04-28 17:48:16
【问题描述】:

我有一个很长的 NSString 并且只想获取适合 CGSize 的字符串。

例子:

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

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

请忽略语法。

从上面的细节我可以得到什么 NSString 适合 CGSize 并得到省略号。

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

【问题讨论】:

标签: ios nsstring


【解决方案1】:

我刚刚在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

【讨论】:

  • 感谢您的回复。会尝试并通知您。
【解决方案2】:

如果您的最终目标是将字符串放入具有固定宽度的 UILabel 中(我在这里做一个假设),那么只需将 NSString 分配给标签并让 UILabel 处理细节(即文本对齐,基线、换行符等)。

如果不是,那么您将不得不遍历字符串,一次增加一个字符的长度,并使用 UIStringDrawing 方法对其进行测量:

- (CGSize)sizeWithAttributes:(NSDictionary *)attrs

别忘了先测量省略号的大小并将其考虑在内。

【讨论】:

  • 对不起,我只需要字符串。如果是 UILabel,那么我什至不会问这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多