问题
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