我正在尝试让 UIWebView 显示一些带有图像的文本。文本中有一些链接,例如:
“我曾经养过一条鱼
http://mysite.com/images/fish.jpg
。我还养过一只小狗和一只公鸡http://mysite.com/images/dog.jpg
”
会导致:
我曾经有一条鱼
----------------------------------
| |
|Fish Image From |
|http://mysite.com/images/fish.jpg|
| |
| |
----------------------------------
我还养了一只小狗和一只公鸡
----------------------------------
| |
|dog Image From |
|http://mysite.com/images/dog.jpg|
| |
| |
----------------------------------
--------------------------------------
| |
|rooster Image From |
|http://mysite.com/images/rooster.jpg|
| |
| |
--------------------------------------
NSMutableString *mutableString = [[NSMutableString alloc] initWithFormat:@"<html><head></head><body>%@</body>",string];
NSString *pattern = @"http://.+\\.(?:jpg|jpeg|png|gif|bmp)";
NSString *replacement = @"<br /><img style=\"width:100%;height:auto;\" src=\"$1\"/><br />";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0 error:NULL];
[regex replaceMatchesInString:mutableString
options:0
range:NSMakeRange(0, mutableString.length)
withTemplate:replacement];
但是当我检查结果时,图像得到了这个:<br /><img style="width:100%;height:auto;" src=""/><br />
并且链接消失了。
图像必须在哪里:
文本...
<br /><img style="width:100%;height:auto;" src="http://mysite.com/images/fish.jpg"/><br />
文本...
<br /><img style="width:100%;height:auto;" src="http://mysite.com/images/dog.jpg"/><br />
<br /><img style="width:100%;height:auto;" src="http://mysite.com/images/rooster.jpg"/><br />