I have to show rich text that i pull from server, so i\'m using UIWebView. Now the problem is that i have no control over the font which is used in UIWebView. How can i chan
System Font
-apple-system on iOS 9 & Safari OS X 10
font-family: -apple-system;
font-family: '-apple-system','HelveticaNeue'; // iOS 8 compatible
I made a method that wraps some text in a HTML body with the correct style for a given UIColor
and UIFont
. It is based on Mustafa answer.
It is used like this:
NSString * htmlString = [MyClass htmlFromBodyString:@"an <b>example</b>"
textFont:[UIFont systemFontOfSize:10]
textColor:[UIColor grayColor]];
[webView loadHTMLString:htmlString baseURL:nil];
I use the following CSS in a web view to do exactly what you are saying.
body
{
font-family:helvetica;
}
But yours looks the like it should work as well. Strange. Only difference I can see is the font vs font-family, but that shouldn't make a difference.
chris.
another easy way that worked for me
UIFont *font = [UIFont systemFontOfSize:15];
NSString *htmlString = [NSString stringWithFormat:@"<span style=\"font-family:Helvetica; font-size: %i\">%@</span>",
(int) font.pointSize,
[bodyText stringWithNewLinesAsBRs]];
[myWebView loadHTMLString:htmlString baseURL:nil];
Here is my easy to use and easy to expand solution with more font settings:
myHTMLLabel = [[UIWebView alloc] initWithFrame:CGRectMake(myX,myY,myWidth,myHeight)];
myHTMLLabel.userInteractionEnabled=NO;
myHTMLLabel.scalesPageToFit=NO;
[myHTMLLabel setOpaque:NO];
myHTMLLabel.backgroundColor = myBackColor;
NSString *myHTMLText = [NSString stringWithFormat:@"<html>"
"<head><style type='text/css'>"
".main_text {"
" display: block;"
" font-family:[fontName];"
" text-decoration:none;"
" font-size:[fontSize]px;"
" color:[fontColor];"
" line-height: [fontSize]px;"
" font-weight:normal;"
" text-align:[textAlign];"
"}"
"</style></head>"
"<body> <SPAN class='main_text'>[text]</SPAN></body></html>"];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[text]" withString: myText];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontName]" withString: myFontName];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontSize]" withString: myFontSize];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[fontColor]" withString: myFontColorHex];
myHTMLText = [myHTMLText stringByReplacingOccurrencesOfString: @"[textAlign]" withString: myFontAlign];
NSLog(@"*** renderHTMLText --> myHTMLText: %@",myHTMLText);
[myHTMLLabel loadHTMLString:myHTMLText baseURL:nil];
It worked when i modified the string like this. Your right chris, it shouldn't make any difference.
NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-family: \"%@\"; font-size: %@;}\n"
"</style> \n"
"</head> \n"
"<body>%@</body> \n"
"</html>", @"helvetica", [NSNumber numberWithInt:kFieldFontSize], content];