插入行时保持相同的NSTableView滚动位置

时间:2017-01-31 18:45:41

标签: macos cocoa nstableview nsscrollview

我有一个基于视图的NSTableView,显示了消息/信息的时间表。行高是可变的。使用insertRows定期在表格顶部添加新消息

NSAnimationContext.runAnimationGroup({ (context) in
    context.allowsImplicitAnimation = true
    self.myTable.insertRows(at: indexSet, withAnimation: [.effectGap])
})

当用户停留在表格的顶部时,消息会一直插入到顶部,从而压低现有消息:在此上下文中的常见行为。

一切正常,除了如果用户向下滚动,新插入的消息不应该使表格滚动

我希望tableView在用户滚动或用户向下滚动时保持原样。

换句话说,如果第一行100%可见, tableView应该只被新插入的行按下。

我试图通过快速恢复这样的位置来表达表格的幻觉:

// we're not at the top anymore, user has scrolled down, let's remember where
let scrollOrigin = self.myTable.enclosingScrollView!.contentView.bounds.origin
// stuff happens, new messages have been inserted, let's scroll back where we were
self.myTable.enclosingScrollView!.contentView.scroll(to: scrollOrigin)

但它并不像我想的那样表现。我尝试了很多组合,但我认为我对剪辑视图,滚动视图和表格视图之间的关系不了解。

或者我可能处于XY问题区域,并且有不同的方法可以解决此问题?

1 个答案:

答案 0 :(得分:4)

忘记滚动视图,剪辑视图,contentView,documentView并专注于表格视图。表格视图可见部分的底部不应移动。您可能错过了翻转的坐标系。

NSPoint scrollOrigin;
NSRect rowRect = [self.tableView rectOfRow:0];
BOOL adjustScroll = !NSEqualRects(rowRect, NSZeroRect) && !NSContainsRect(self.tableView.visibleRect, rowRect);
if (adjustScroll) {
    // get scroll position from the bottom: get bottom left of the visible part of the table view
    scrollOrigin = self.tableView.visibleRect.origin;
    if (self.tableView.isFlipped) {
        // scrollOrigin is top left, calculate unflipped coordinates
        scrollOrigin.y = self.tableView.bounds.size.height - scrollOrigin.y;
    }
}

// insert row
id object = [self.arrayController newObject];
[object setValue:@"John" forKey:@"name"];
[self.arrayController insertObject:object atArrangedObjectIndex:0];

if (adjustScroll) {
    // restore scroll position from the bottom
    if (self.tableView.isFlipped) {
        // calculate new flipped coordinates, height includes the new row
        scrollOrigin.y = self.tableView.bounds.size.height - scrollOrigin.y;
    }
    [self.tableView scrollPoint:scrollOrigin];
}

我没有测试" tableView在用户滚动的时候保持原状#34;。

相关问题