I am looking for a simple way to use NSAttributedString
with a very simple message box similar to:
NSString *new_item = [NSString stringWithFormat:@"<span style=\"font-family: Helvetica Neue; font-size: 12.0\">%@</span>", @"MOTD HTML String downloaded from website"];
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[new_item dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"MOTD"
message:attrStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
My above code takes a HTML formatted string that has been downloaded from a server, makes sure the text size will fit the screen properly, then tries to send the NSAttributedString
to the UIAlertView
. But UIAlertView
does not like this. what would be the simplest way around this problem?(Non HTML formatted MOTD is not an option)
Add your attributed string to label and add it as assessoryView to alert
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Test Attributed String" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:@"Hello red"];
[attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attributedStr;
lbl.textAlignment = NSTextAlignmentCenter;
[alert setValue:lbl forKey:@"accessoryView"];
[alert show];
Now a days UIAlertView
is deprecated. You can use UIAlertController
.