我正在尝试将工具栏添加到UIWebView上。我有一个表格视图,当一行被选中时,它会推送一个UIWebView,在那个web视图中,我想要一个工具栏,我可以在其中添加前进和后退按钮。我正在阅读一本关于iOS编程的书,这就是他们要求完成练习的方式。到目前为止,我还不能让工具栏真正显示在WebView中,所以我的问题是,在让工具栏显示时,我做错了什么?下面是我的UIWebViewController.m中的代码
UIWebView *webView = [[UIWebView alloc] init];
webView.scalesPageToFit = YES;
self.view = webView;
CGRect frame = CGRectMake(0, 0, 360,44);
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame: frame];
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target:self action:@selector(goBack)];
NSArray *items = [[NSArray alloc] initWithObjects:back, nil];
[toolBar setItems:items animated:YES];
[self.view addSubview:toolBar];
[self.view bringSubviewToFront:toolBar];当我运行此命令时,工具栏不显示。我已经尝试了很多不同的配置来定位实际的CGRect框架,但没有。更让我困惑的是,如果我使用相同的代码(对工具栏视图进行一些修改并将其放入测试项目中的应用程序委托中,工具栏就会显示出来。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 44, [[UIScreen mainScreen] bounds].size.width, 44)];
toolBar.barStyle = UIBarStyleDefault;
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target:self action:nil];
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:self action:@selector(goBack)];
UIBarButtonItem *forward = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:self action:@selector(goForward)];
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:space];
[items addObject:back];
[items addObject:forward];
[toolBar setItems:items animated:YES];
[self.window addSubview:toolBar];
return YES;发布于 2015-07-20 02:27:55
就创建UIToolbar而言,代码看起来还不错,但我认为在您创建它的时候,self.view可能并不存在,或者self.window在那一刻仍然是空的。
确保在viewWillAppear或viewDidLoad方法中调用代码,此时self.view和self.window都存在。
===编辑===
我认为另一个问题是您将其添加为UIWebView的子视图。尝试将UIWebView添加为视图的子视图。
[self.view addSubview:webView]如果你从nib加载东西,你这样做似乎是错误的,你不应该以这种方式覆盖view。
https://stackoverflow.com/questions/31504387
复制相似问题