组合 x 个属性字符串

Combined x numbers of attributed strings

我想问一下如何将x个属性字符串合并成一个字符串。

    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:health.storeArry];
            NSLog(@"%lu",(unsigned long)array.count);
            for (NSDate * str in array) {
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                dateFormatter.timeZone = [NSTimeZone localTimeZone];
                dateFormatter.timeStyle = NSDateFormatterShortStyle;
                NSString * dateTimeString = [dateFormatter stringFromDate:str];

                NSString* str=dateTimeString;
                NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:str];

                [attrString addAttribute: NSFontAttributeName value:  [UIFont fontWithName:@"Helvetica" size:15] range: NSMakeRange(str.length-2,2)];
                NSLog(@"%@",attrString);

                [attrString appendAttributedString:attrString];

}

这是我的代码。我发现两个或三个 attibutedstring 的 ans 被串联,但我有一个数组,其中 x number nsdate 个对象。我想将它们全部连接成一个字符串。我怎样才能做到这一点? 谢谢

做这样的事情,

NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
NSMutableString *str = [[NSMutableString alloc]init];

for (int i = 0; i < arr.count; i++) {

    str = [str stringByAppendingString:[arr objectAtIndex:i]];

}
NSLog(@"final str is %@",str);

希望这会有所帮助:)

更新:

你可以转换成NSString喜欢,

NSString *str1 =  [NSString stringWithFormat:@"%@", nsattributedstring];

然后你可以附加它。所以从数组中获取属性字符串,将其转换为 nsstring 并附加它。

您的问题是您每次都在创建一个新的 NSMutableAttributedString。你需要把它放在for循环之外。

NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:health.storeArry];
NSLog(@"%lu",(unsigned long)array.count);

NSMutableAttributedString *finalAttributedString = [NSMutableAttributedString alloc] init];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;

for (NSDate *str in array) {

    NSString *dateTimeString = [dateFormatter stringFromDate:str];

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:dateTimeString];

    [attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica" size:15] range:NSMakeRange(str.length-2,2)];
     NSLog(@"%@",attrString);

    [finalAttributedString appendAttributedString:attrString];

}
//Here, you can read the finalAttributedString

不相关提示:您应该在 for 循环之外 alloc/init NSDateFormatter。一直都是一样的,加上alloc/init of NSDateFormatter 就很消耗了。