我为 OS X 10.9 和 OS X 10.10 开发了一个应用程序。此应用程序有 2 个 View :
- 登录 View
- 历史 View
在登录 View 中,用户应仅插入用户名和密码。当用户按下登录按钮时,它会调用 Web 服务来授权用户查看新闻。
当用户登录时,应用程序会显示历史记录 View ,其中存储了所有发送的新闻。为了检索此新闻,它调用 Web 服务来获取包含所有新闻历史记录的 JSON。为了显示所有新闻,我使用了 NSTableView。
当用户将鼠标移到此 NSTableView
的一行上时,该行的背景变为灰色。
一切都工作得很好,但为了保持更新新闻列表,我必须每 10 秒调用一次 Web 服务来获取历史新闻,因此我将以下代码放入我的 HistoryViewController
中:
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(sendRequestToUrl) userInfo:nil repeats:YES];
其中 sendRequestToUrl
是从 Web 服务获取历史记录的方法。因此,每次重新加载新闻列表时,它都会在没有鼠标悬停的情况下向我显示一行结束。这是为什么?
为了将鼠标悬停在上面,我在自定义单元类中插入以下代码:
#import "HistoryCustomCell.h"
@implementation HistoryCustomCell {
NSTrackingArea *_trackingArea;
NSEvent *event;
}
- (void)awakeFromNib {
[self createTrackingArea];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
- (void)createTrackingArea {
_trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingActiveInActiveApp owner:self userInfo:nil];
[self addTrackingArea:_trackingArea];
NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];
mouseLocation = [self convertPoint:mouseLocation fromView:nil];
if (NSPointInRect(mouseLocation, [self bounds])) {
[self mouseEntered:nil];
} else {
[self mouseExited:nil];
}
}
- (void)mouseEntered:(NSEvent *)theEvent {
[self.onMouseOverImage setImage:[NSImage imageNamed:@"mouse_over_back_cell.png"]];
}
- (void)mouseExited:(NSEvent *)theEvent {
[self.onMouseOverImage setImage:[NSImage imageNamed:nil]];
}
@end
知道为什么它不能正常工作吗?
谢谢
最佳答案
基于 View 的表格 View 在不同时间重复使用不同单元格(行)的单元格 View 。因此,一旦您设置了单元格 View 的 subview 之一的图像,即使该单元格 View 从表格中删除然后添加回表格以用于其他单元格,它也会保持这种状态。
您可以尝试覆盖 -prepareForReuse
并将所有可以自定义的内容重置回默认状态。
无论如何,您通常应该在覆盖整个 View 的跟踪区域的选项中指定 NSTrackingInVisibleRect
。这使得 AppKit 在 View 移动或更改大小时保持跟踪区域更新到 View 在屏幕上的位置,尤其是在 ScrollView 中时。否则,您必须重写 -updateTrackingAreas
来删除并重新添加 View 新位置的跟踪区域。
关于objective-c - 鼠标悬停在 NSTableCellView 上时随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078605/