gpt4 book ai didi

objective-c - 可拖动的 NSView

转载 作者:行者123 更新时间:2023-12-03 17:05:20 25 4
gpt4 key购买 nike

如何以编程方式创建 NSView 以便用户可以用鼠标移动其位置?我需要为 View 分配哪些属性?谢谢!

    newView = [helpWindow contentView];
[contentView addSubview:newView];
//add properties of newView to be able to respond to touch and can be draggable

最佳答案

不幸的是,没有像 setMoveByWindowBackground: 这样的简单方法可以对窗口进行操作。您必须重写 mouseDown:、mouseDragged: 和 mouseUp: 并根据鼠标指针的位置使用 setFrameOrigin:。为了在您首次单击 View 内部时不发生 View 跳转,您还需要考虑 View 原点与首次单击时鼠标指针在 View 中的位置之间的偏移量。这是我在一个项目中制作的一个示例,用于在父 View 中移动“图 block ”(这是游戏“Upwords”的计算机版本,类似于 3d 拼字游戏)。

-(void)mouseDown:(NSEvent *) theEvent{
self.mouseLoc = [theEvent locationInWindow];
self.movingTile = [self hitTest:self.mouseLoc]; //returns the object clicked on
int tagID = self.movingTile.tag;
if (tagID > 0 && tagID < 8) {
[self.viewsList exchangeObjectAtIndex:[self.viewsList indexOfObject:self.movingTile] withObjectAtIndex: 20]; // 20 is the highest index in the array in this case
[self setSubviews:self.viewsList]; //Reorder's the subviews so the picked up tile always appears on top
self.hit = 1;
NSPoint cLoc = [self.movingTile convertPoint:self.mouseLoc fromView:nil];
NSPoint loc = NSMakePoint(self.mouseLoc.x - cLoc.x, self.mouseLoc.y - cLoc.y);
[self.movingTile setFrameOrigin:loc];
self.kX = cLoc.x; //this is the x offset between where the mouse was clicked and "movingTile's" x origin
self.kY = cLoc.y; //this is the y offset between where the mouse was clicked and "movingTile's" y origin
}
}

-(void)mouseDragged:(NSEvent *)theEvent {
if (self.hit == 1) {
self.mouseLoc = [theEvent locationInWindow];
NSPoint newLoc = NSMakePoint(self.mouseLoc.x - self.kX, self.mouseLoc.y - self.kY);
[self.movingTile setFrameOrigin:newLoc];
}
}

这个例子指出了另一种可能的复杂情况。当您移动 View 时,它可能会出现在其他 View 下方移动,因此我负责将移动 View 设为父 View subview 的最顶层 View (viewsList 是从 self.subviews 获取的数组)

关于objective-c - 可拖动的 NSView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9962769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com