我有以下代码以编程方式创建UIWebView并在其上创建UIButton以关闭它.创建没问题,但问题是我无法再参考创建的UIWebView来关闭按钮!
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(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 { ???? }
感谢您提前的帮助:)
解决方法
在ViewController.m中
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,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,40); [button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside]; [webView addSubview:button]; - (IBAction)close:(id)sender { [[self.view viewWithTag:55] removeFromSuperview]; }