我有iphone应用程序我已经创建了一个组合框我希望组合框应该从xcode直接获取值而不是来自html文件所以如何做到这一点我使用以下代码来获取html文件中的组合框
NSString *htmlPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"combo.html"];
NSString *htmlContent = [NSString stringWithContentsOfFile:htmlPath];
[webView loadHTMLString:htmlContent baseURL:nil];
combo.html:
<html>
<SELECT NAME="food" SIZE="10" style="width: 200px;" style="height: 100px ">
<OPTION VALUE="0">OK</OPTION>
<OPTION VALUE="1">Good</OPTION>
<OPTION VALUE="2">Best</OPTION>
<OPTION VALUE="3">Average</OPTION>
</SELECT>
</html>
答案 0 :(得分:0)
我不是百分百肯定我理解这个问题,但我认为您是在询问是否可以从应用包中加载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文件,则可能需要稍微优化一下。