Search code examples
objective-cmacoswebviewaddsubviewnsscrollview

How do I add a subView to a webView in OS X so It will scroll


This should work but doesn't. Something similar will work in iOS though.

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
    NSView<WebDocumentView>* doc = [[[self.webView mainFrame] frameView] documentView];
    TestView* testView = [[TestView alloc]init];
    [testView setFrame:CGRectMake(200, 400, 100, 50)];
    NSScrollView* sv = [doc enclosingScrollView];
    [sv addSubview:testView];
    [self.webView setNeedsDisplay:YES];
}

testView appears but will not scroll along with doc. Adding it to sender produces the same results. Adding testView to doc produces no visible effect.

If no one knows another way to do it, I should be able to do it with live scrolling notifications .

Thanks

I have done as you suggest. The demo app is at: https://dl.dropboxusercontent.com/u/108679476/webDemo.zip

I have experimented with setNeedsDisplay for webView, doc, and sv. The AddToScrollView button works but will not scroll or magnify. The AddToDoc buttons does not work under any conditions that I have tried.

Is it possible that the scrollView is ignoring setNeedsDisplay because it doesn't know that doc has been changed?

Thanks


Solution

  • It wasn't moving because you were adding it to NSClipView. As mentioned in comment it should be added into documentView. Once I did it I faced issue that I wasn't able to see the view. So I started tool called "Interface Inspector" and verified the view. It was there, correctly moving but not being drawn. So I changed your view to be layer backed and it started to work.

    -(IBAction)addToScrollView:(id)sender
    {
      NSView<WebDocumentView>* doc = [[[self.webView mainFrame] frameView] documentView];
      TestView* testView = [[TestView alloc]init];
      [testView setFrame:CGRectMake(200, self.currentSVYCoordinate, 100, 50)];
      testView.wantsLayer = YES;
      CALayer *layer = [[CALayer alloc] init];
      layer.backgroundColor = [[NSColor redColor] CGColor];
      testView.layer = layer;
      self.currentSVYCoordinate = self.currentSVYCoordinate + 200;
      NSScrollView* sv = [doc enclosingScrollView];
      NSView *documentView  = [sv documentView];
      [documentView addSubview:testView];
      [sv setNeedsDisplay:YES];
    }