For my app, I have a UIToolBar that appears above a UIWebView. What I'm attempting to do is remove both the tool-bar and the web-view from the superview when UIBarButtonItem in the tool-bar is clicked.
I've made the tool-bar and web-view properties of my ViewController like so:
@property (nonatomic, weak) UIToolbar *toolBar;
@property (nonatomic, weak) UIWebView *webView;
These views are supposed to be removed when the method below is called
// Remove the toolbar and the webview
- (void)hideToolbarAndWebView
{
[_toolBar removeFromSuperview];
[_webView removeFromSuperview];
NSLog(@"Button clicked");
}
Below is where I'm first creating the bar-button item, and assigning the action to be the hideToolbarAndWebView method:
// Create a bar button and add it to the toolbar. Action is to dismiss the tool-bar and thew web-view.
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(hideToolbarAndWebView)];
I know that the bar-button is successfully calling the hideToolbarAndWebView method through logging, but the views are not being removed from the superview. How do I fix this?
EDIT Below is the code where the tool-bar is created. It's inside a method called showToolbar
that is called from the AppDelegate.
// Create a toolbar
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:self.view.bounds];
toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Default height is 44 points, but seems to close to the status bar
toolBar.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),64);
toolBar.barStyle = UIBarStyleBlackTranslucent;
[self.view addSubview:toolBar];
Below is the code that creates the web-view, and calls the above showToolbar
method:
// Create a web view that displays the update info, and save settings for current version
SWWebViewController *webViewController = [[SWWebViewController alloc] init];
NSString *url=@"http://google.com";
webViewController.URL = url;
webViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.navigationController presentViewController:webViewController animated:YES completion:nil];
[webViewController showToolbar];
Thanks to @Midhun MP, I realized what I was doing wrong. Instead of trying to use properties, I needed to set toolBar
and webView
to be global variables:
UIToolbar *toolBar;
UIWebView *webView;
And instead of creating toolBar
and webView
like so:
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:self.view.bounds];
SWWebViewController *webViewController = [[SWWebViewController alloc] init];
Since the variables were now created, I now only needed to assign them like so:
toolBar = [[UIToolbar alloc] initWithFrame:self.view.bounds];
webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
Then, when I called hideToolbarAndWebView
, the toolBar
and webView
were both removed from the superview.