我不确定你获取细胞的方法有什么问题,但你真的不需要这样做来做你想做的事。我测试了一种方法来执行此操作,该方法需要创建一个表视图子类来在鼠标移动方法中进行跟踪。这是该子类的代码:
-(void)awakeFromNib {
NSTrackingArea *tracker = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveInActiveApp owner:self userInfo:nil];
[self addTrackingArea:tracker];
self.rowNum = -1;
}
-(void)mouseMoved:(NSEvent *)theEvent {
NSPoint p = theEvent.locationInWindow;
NSPoint tablePoint = [self convertPoint:p fromView:nil];
NSInteger newRowNum = [self rowAtPoint:tablePoint];
NSInteger newColNum = [self columnAtPoint:tablePoint];
if (newColNum != self.colNum || newRowNum != self.rowNum) {
self.rowNum = newRowNum;
self.colNum = newColNum;
[self reloadData];
}
}
-(void)mouseEntered:(NSEvent *)theEvent {
[self reloadData];
}
-(void)mouseExited:(NSEvent *)theEvent {
self.rowNum = -1;
[self reloadData];
}
我将数组和表委托以及数据源代码放在了应用委托中(可能不是最好的地方,但可以进行测试)。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.theData = @[@{@"name":@"Tom",@"age":@"47"},@{@"name":@"Dick",@"age":@"21"},@{@"name":@"Harry",@"age":@"27"}];
[self.table reloadData];
self.dict = [NSDictionary dictionaryWithObjectsAndKeys:@2,NSUnderlineStyleAttributeName,[NSColor redColor],NSForegroundColorAttributeName,nil];
}
- (NSInteger)numberOfRowsInTableView:(RDTableView *)aTableView {
return self.theData.count;
}
- (id)tableView:(RDTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
if (self.table.colNum == 0 && rowIndex == self.table.rowNum && [aTableColumn.identifier isEqualToString:@"Link"]) {
NSString *theName = [[self.theData objectAtIndex:rowIndex] valueForKey:@"name"];
return [[NSAttributedString alloc] initWithString:theName attributes:self.dict];
}else if ([aTableColumn.identifier isEqualToString:@"Link"]){
return [[self.theData objectAtIndex:rowIndex] valueForKey:@"name"];
}else{
return [[self.theData objectAtIndex:rowIndex] valueForKey:@"age"];
}
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
if (self.table.colNum == 0)
NSLog(@"%ld",[aNotification.object selectedRow]);
}
如果您单击第一列中的单元格(在 IB 中设置了标识符“Link”),我使用委托方法 tableViewSelectionDidChange: 来实现该操作。