ios - 从 NSString 更改为 NSAttributedString 时缺少一些方法

标签 ios objective-c nsstring nsattributedstring

大家好 :) 我有一种方法,可以在给定数量的单词后剪切一段长文本。它看起来像这样:

NSString *trimString(NSString *string, int length, Boolean soft) {
if(string == Nil || string.length == 0){
    return string;
}

NSMutableString *sb = [[NSMutableString alloc]init];
int actualLength = length - 3;
if(string.length > actualLength){
    // -3 because we add 3 dots at the end. Returned string length has to be length including the dots.
    if(!soft) {
        [sb appendString:[string substringToIndex:actualLength - 3]];
        [sb appendString:@"..."];
        return sb;
    } else {
        NSRange r = NSMakeRange(0, actualLength);
        //NSRange range = [string rangeOfString:@" " options:NSBackwardsSearch range:r];
        NSRange range = [string rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@" \n\r\t"] options:NSBackwardsSearch range:r];
        [sb appendString:[string substringToIndex:range.location]];
        [sb appendString:@"..."];
        return sb;
    }
}
return string;
}

我的问题是我必须将所有内容更改为 NSAttributedString,但是没有像“substringToIndex:”这样的东西,所以我可以更改它.... 甚至可以更改它吗?

谢谢!

最佳答案

您可以通过引用属性字符串上的 string 属性来对 NSString 支持的 NSAttributedString 执行任何操作。这是底层的 NSString,你可以随心所欲地使用它。

关于ios - 从 NSString 更改为 NSAttributedString 时缺少一些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609819/

相关文章:

iphone - iOS - 如何在更改 View 时停止背景音乐

ios - 字典给出不正确的值

ios - NSDateFormatter错误,返回日期一年前

iphone - iOS 4.2.1 开发 SDK 中缺少 libXcodeDebuggerSupport.dylib

ios - 发送同步请求 :urlrequest returningResponse:&responce error:&error is unavilable in WatchOS2

objective-c - 如何在 Objective C 中使用 DTO

ios - 我编写的由 GCD 代码支持的读写锁导致并行测试死锁

ios - 为什么我的 CGPoints 全部返回为 {0,0}?

ios - NSBundle pathForResource : returns nil

ios - 自动编辑 NSString?