Why isnt this variable an Attributed String?

醉酒当歌 提交于 2019-12-11 17:56:56

问题


I have these 3 lines in code which are meant to take text from a .txt file and allocate it to an NSAttributedString

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text];

Using the debugger I know that the path is being found correctly, and the text is being added to the variable text fine, but its not converting to the NSAttributedString - the debugger just says "variable is not NSAttributedString"

What am I missing from the third line to allow the NSString to be converted to an NSSAttributedString? (I dont want any attributes, but Im presuming you can just load the string into an attributed string?)


回答1:


The problem might come from somewhere else I guess, just tried :

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text];

NSLog(@"Text : %@\nNSAS : %@", text, attString);

Here is the output :

2013-06-10 11:17:04.444 TestsSO[5554:c07] Text : hello, world !
NSAS : hello, world !{
}

Are you sure that text is filled correctly ?




回答2:


try with

NSAttributedString *attString = [[NSAttributedString alloc] initWithString:text attributes:nil];

Hope it will work.




回答3:


Try

NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:text];


  [attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15] range:NSMakeRange(0, 15)]; // Begin and Last letter

        [attri_str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0/255.0 green:143/255.0 blue:255/255.0 alpha:0.75] range:NSMakeRange(0,25)];

I hope it help for you.



来源:https://stackoverflow.com/questions/17020396/why-isnt-this-variable-an-attributed-string

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