首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

macOS NSTableView 逐行高亮動畫實作:Timer + selectRow 完整範例

     編輯:程式設計綜合問答

需求場景

點擊 Start 按鈕後,NSTableView 從第一列開始逐行高亮選取,每列停留數秒,類似播放清單的當前播放指示器。

核心實作:NSTimer + selectRowIndexes

@property (strong) NSTimer *highlightTimer;
@property (assign) NSInteger currentRow;

- (IBAction)startHighlight:(id)sender {
    self.currentRow = 0;
    self.highlightTimer = [NSTimer scheduledTimerWithTimeInterval:2.0  // 每列停留 2 秒
        target:self selector:@selector(highlightNextRow:) userInfo:nil repeats:YES];
}

- (void)highlightNextRow:(NSTimer *)timer {
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:self.currentRow];
    [self.tableView selectRowIndexes:indexSet byExtendingSelection:NO];
    [self.tableView scrollRowToVisible:self.currentRow]; // 確保可見
    
    self.currentRow++;
    if (self.currentRow >= [self.tableView numberOfRows]) {
        [timer invalidate];
        self.highlightTimer = nil;
    }
}

關鍵細節

  • selectRowIndexes:byExtendingSelection: 第二參數 NO 表示單選模式,取消先前選取。
  • scrollRowToVisible: 防止高亮行超出可視區域。
  • 在 viewDidDisappear 或 dealloc 中 [timer invalidate] 避免洩漏。

進階:自訂高亮樣式

實作 NSTableViewDelegate 的 tableView:rowViewForRow: 回傳自訂 NSTableRowView,覆寫 drawSelectionInRect: 繪製漸層、脈動動畫等效果。

  1. 上一篇文章:
  2. 下一篇文章: