好的,我制作了一个简单的视图控制器,它像您尝试做的那样手动将 UIWebView 添加到自身。它也是一个私有的 UIWebView。我创建了一个简单的按钮,它将一个传递alert()
给 UIWebView 并且它每次都有效,所以这里是整个代码,所以你可以看到发生了什么。
.h 文件
#import <UIKit/UIKit.h>
@interface SOFViewController : UIViewController
// This is linked as action thru nib.
- (IBAction)hitMe:(UIButton *)sender;
@end
.m 文件
这里请注意我第一次调用 javascript 到 webView 中的位置ViewDidAppear
,其他前面的函数在第一次在模拟器中启动时会导致不良行为。我正在使用 Xcode 4.3
#import "SOFViewController.h"
@interface SOFViewController ()
{
int idNumber;
UIWebView *webViewMain;
}
@end
@implementation SOFViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
webViewMain = [[UIWebView alloc] initWithFrame:CGRectMake(50.0, 50.0, 50.0, 50.0)];
[self.view addSubview:webViewMain];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
idNumber = idNumber + 1;
NSString * js = [NSString stringWithFormat:@"alert('%d');",idNumber];
[webViewMain stringByEvaluatingJavaScriptFromString:js];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)hitMe:(UIButton *)sender {
idNumber = idNumber + 1;
NSString * js = [NSString stringWithFormat:@"alert('%d');",idNumber];
[webViewMain stringByEvaluatingJavaScriptFromString:js];
}
@end
希望这有一些帮助。