我有以下代码以编程方式创建UIWebView并在其上创建UIButton以关闭它。创建没问题,但问题是我无法回复创建的UIWebView来关闭按钮!
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Close" forState:UIControlStateNormal];
button.frame = CGRectMake(80, 210, 160, 40);
[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[webView addSubview:button];
- (IBAction)close:(id)sender {
????
}
提前感谢您的帮助:)
答案 0 :(得分:14)
在ViewController.m中
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
// tag will be used to get this webview later
webView.tag=55;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self.view addSubview:webView];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(close:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Close" forState:UIControlStateNormal];
button.frame = CGRectMake(80, 210, 160, 40);
[button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
[webView addSubview:button];
- (IBAction)close:(id)sender {
[[self.view viewWithTag:55] removeFromSuperview];
}
答案 1 :(得分:0)
将您的webView保持为UIViewController的ivar。
现在您将它作为方法的局部变量,因此您无法在该方法之外引用它。相反,在.h文件的界面部分声明它,您将能够从所有类方法中访问它。
不要忘记在dealloc方法中释放它!
答案 2 :(得分:0)
网页视图是按钮的超级视图,因此你应该能够像这样获得它,
UIWebView * webView = [(UIButton *)sender superview];
现在你可以removeFromSuperview
或其他东西让它消失。
修改强>
- (IBAction)close:(id)sender {
UIWebView * webView = [(UIButton *)sender superview];
[webView removeFromSuperview];
}
答案 3 :(得分:-1)
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@",request.URL.absoluteString);
NSString *absoluteUrl = [[request URL] absoluteString];
if ([absoluteUrl isEqualToString:@"https://google.com/login?"]) {
NSLog(@"move to another view or close the web view");
[portfolioWebView removeFromSuperview];
return NO;
}
return YES;
}