1

我创建了一个图像视图

for(int i=0; i<pcount; i++)
{
    int x = rand() % 350;
    int y = rand() % 350;
    NSRect rect = NSMakeRect((x+10),(y+10), 200, 200);
    //NSImageView *imageView 
    imageView1 = [[NSImageView alloc]initWithFrame:rect];
    [imageView1 setTag:i];

    // imageView = [[NSImageView alloc]initWithFrame:rect];
   // [imageView1 rotateByAngle:rand() % 150];

    [imageView1 setImageScaling:NSScaleToFit];
    [imageView1 canBecomeKeyView];
    NSImage *theImage = [[NSImage alloc]initWithContentsOfURL:(NSURL*)[patharray objectAtIndex:(i)]];
    [imageView1 setImage:theImage];
    [[imageView1 cell] setHighlighted:YES];
    [[layoutCustom view] addSubview:imageView1 positioned:NSWindowMovedEventType relativeTo:nil];}    

现在如何通过鼠标单击选择每个图像视图?提前致谢。

4

2 回答 2

1

我在这里假设您有理由不使用现有的集合视图。因此,从我在您的代码中读到的内容中,您有 layoutCustom.view,其中包含一堆 NSImageView。这里有两个选项:

  1. 在您的 layoutCustom 对象中实现 mouseDown: (或 mouseUp: 或两者)。将事件位置转换为视图坐标并查找 CGRectContainsPoint(subview.frame, mouseDownPoint) 返回 YES 的任何子视图。您应该选择该视图。

  2. 继承 NSImageView 并实现 mouseDown: (或 mouseUp: 或两者)。在 mouseDown 上:只需设置一个“选定”标志。视图可以在选择时自己绘制某些东西,或者 layoutCustom 对象可以观察属性并相应地绘制选择。

我更喜欢选项 1,因为它更简单,需要更少的类和更少的对象之间的交互。

// Option 1 (in layoutCustom class)

- (void) mouseDown:(NSEvent*)theEvent {
    CGPoint mouseDownPoint = [self convertPoint:theEvent.locationInWindow fromView:nil];
    for (NSView *view in self.subviews) {
        if (CGRectContainsPoint(view.frame, mouseDownPoint)) {
            // Do something to remember the selection.
            // Draw the selection in drawRect:
            [self setNeedsDisplay:YES];
        }
    }
}




// Option 2 (in Custom subclass of NSImage)

- (void) mouseDown:(NSEvent*)theEvent {
    self.selected = !self.selected;
}


// Option 2 (in layoutCustom class)
- (void) addSubview:(NSView*)view positioned:(NSWindowOrderingMode)place relativeTo:(NSView*)otherView {
    [super addSubview:view positioned:place relativeTo:otherView];
    [self startObservingSubview:view];
}

- (void) willRemoveSubview:(NSView*)view {
    [self stopObservingSubview:view];
}

- (void) startObservingSubview:(NSView*)view {
   // Register your KVO here
   // You MUST implement observeValueForKeyPath:ofObject:change:context:
}

- (void) stopObservingSubview:(NSView*)view {
   // Remove your KVO here
}
于 2013-04-11T07:21:23.067 回答
0

我有一个更好的主意:与其将视图中的鼠标点击转换为坐标,然后弄清楚如何将其映射到正确的子视图或子图像,不如先拥有一个大(或滚动?)视图然后将您的图像添加为巨大的“ NSButton”对象(设置为自定义类型),其中按钮图像可以是您要添加的图像。

至于如何选择每个图像?您可以继承“ NSButton”并跟踪其中的一些自定义数据,或者您可以使用“ tag”来确定在您的“”方法中按下了哪个按钮IBAction,然后决定如何处理它。

另一种方法可能是将图像嵌入到 NSTableView 单元格中......

于 2013-04-10T04:53:10.227 回答