无法拖动或移动自定义NSWindow

4

我使用Interface Builder创建了一个NSWindowControllerNSViewController,然后我移除了NSWindow的标题栏,以便自定义窗口。我创建了一个继承NSWindow的类,并在类中执行以下操作。

override var canBecomeKey: Bool {
    return true
}

override var canBecomeMain: Bool {
    return true
}

我还在NSWindowController中设置了这些内容:

{  
    self.window?.becomeKey()
    self.window?.isMovableByWindowBackground = true
    self.window?.isMovable = true;
    self.window?.acceptsMouseMovedEvents = true
}

从这里开始,自定义窗口可以被拖动,
但是当我将NSViewController作为NSWindowControllerContentViewController时,我无法拖动customWindow

可能出了什么问题?

2个回答

0
这里的控制因素是视图的 mouseDownCanMoveWindow 属性。默认情况下,它取决于其 isOpaque 属性。如果您或您的超类之一覆盖了 isOpaque 以返回 true,则 mouseDownCanMoveWindow 的默认实现将返回 false。如果您希望它有不同的行为,则也必须覆盖它。

我已经找到了我的问题,当我拖拽的时候,实际上拖拽的是NSViewController的视图。我让窗口变得不可见,我以为它是窗口,但其实不是。我仍然困惑于通过xib在自定义窗口中添加视图可以工作,但在自定义窗口中添加控制器的视图就无法工作。 - J.Wu

0

我以前也遇到过这个问题,以下是我的解决方案(虽然是用Objective-C编写的,但如果有帮助的话就分享一下):

@property BOOL mouseDownInTitle;

- (void)mouseDown:(NSEvent *)theEvent
{
   self.initialLocation = [theEvent locationInWindow];
   NSRect windowFrame = [self frame];
   NSRect titleFrame = NSMakeRect(0, windowFrame.size.height-40, windowFrame.size.width, 40);
   NSPoint currentLocation = [theEvent locationInWindow];

   if(NSPointInRect(currentLocation, titleFrame))
   {
      self.mouseDownInTitle = YES;
   }
}

- (void)mouseDragged:(NSEvent *)theEvent
{
   if( self.mouseDownInTitle )
   {
      NSRect screenVisibleFrame = [[NSScreen mainScreen] visibleFrame];
      NSRect windowFrame = [self frame];

      NSPoint newOrigin = windowFrame.origin;
      NSPoint currentLocation = [theEvent locationInWindow];



      // Update the origin with the difference between the new mouse location and the old mouse location.
      newOrigin.x += (currentLocation.x - self.initialLocation.x);
      newOrigin.y += (currentLocation.y - self.initialLocation.y);

      // Don't let window get dragged up under the menu bar
      if ((newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)) {
         newOrigin.y = screenVisibleFrame.origin.y + (screenVisibleFrame.size.height - windowFrame.size.height);
      }

      [self setFrameOrigin:newOrigin];
   }
}

我已经尝试了你建议的方法,但它并没有对我起作用。当我拖动视图时,它会消失,我想可能是我拖动的视图框架设置有误。 - J.Wu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接