我不是 100% 确定我理解了这个问题,但我认为您是在问是否可以从您的应用程序包中加载 HTML 文件,然后从您的应用程序中动态插入一些不同的 HTML 内容......对吗?
如果是这样,你当然可以这样做。
首先,我们将内容加载到可变字符串中:
NSString *htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"combo.html"];
NSError *error;
NSMutableString *htmlContent = [NSMutableString stringWithContentsOfFile: htmlPath
encoding: NSUTF8StringEncoding
error: &error];
要在组合框中插入新选项/值,请使用以下内容:
// look for the start of the combo box called "food"
NSRange range = [htmlContent rangeOfString: @"select name=\"food\""
options: NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
// search for the end tag </select>
range.length = htmlContent.length - range.location;
NSRange end = [htmlContent rangeOfString: @"</select>"
options: NSCaseInsensitiveSearch
range: range];
if (end.location != NSNotFound) {
NSString *newChoice = @"Awesome!"; // get this dynamically however you want
NSString *newOption =
[NSString stringWithFormat: @"<option value=\"4\">%@</option>\n", newChoice];
[htmlContent insertString: newOption atIndex: end.location];
NSLog(@"htmlContent = %@", htmlContent);
}
}
如果要更改现有组合框选项的显示值,请使用如下代码:
NSString *optionTwoHtml = @"<option value=\"2\">";
NSRange optionTwo = [htmlContent rangeOfString: optionTwoHtml
options: NSCaseInsensitiveSearch];
if (optionTwo.location != NSNotFound) {
int start = optionTwo.location + optionTwoHtml.length;
// search for the end tag </option>
optionTwo.length = htmlContent.length - optionTwo.location;
NSRange end = [htmlContent rangeOfString: @"</option>"
options: NSCaseInsensitiveSearch
range: optionTwo];
if (end.location != NSNotFound) {
NSString *newValue = @"Better Than Best!";
NSRange oldRange = NSMakeRange(start, end.location - start);
[htmlContent replaceCharactersInRange: oldRange
withString: newValue];
NSLog(@"htmlContent = %@", htmlContent);
}
}
请注意,此代码仅向您展示了您可以做什么。它没有针对性能进行优化。您显示的 HTML 内容非常小,因此解析代码的效率实际上并不重要。如果您使用更大的 HTML 文件,您可能需要稍微优化一下。