NSTableViewで選択された行のテキストが黒字になってしまう場合の対処法


概要

  • 選択時のテキストの色が白色にならず黒色のままになる現象が起きた。
  • また10.14のみで発生。

非選択時

選択時(macOS 10.14)

選択時(macOS10.13.6)

解決法

  • テキストの色をblackColorと指定していたのが原因。
  • セルのテキストnデフォルトで設定されているNSColor.controlTextColorを指定するのが良い。
  • 上記の画像の通り、10.14からNSColorの処理に変化があったのだろう。

参考

今回使用したコード

  • レガシーなcell baseのテーブルビューです。
  • セルの表示時に呼ばれる以下のメソッドでテキストの色を設定します。
- (void)tableView:(NSTableView *)tableView
  willDisplayCell:(id)cell
   forTableColumn:(NSTableColumn *)tableColumn
              row:(NSInteger)row {

AppDelegate.m

#import "AppDelegate.h"
#import "TableViewController.h"

@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@property TableViewController *tableViewController;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    TableViewController *tableViewController = [[TableViewController alloc] init];
    [tableViewController showWindow:self];
    _tableViewController = tableViewController;
}


- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

@end

TableViewController.m

//
//  TableViewController.m
//  NSTableView_SelectedRowTextColor

#import "TableViewController.h"

@interface TableViewController ()<NSTableViewDelegate, NSTableViewDataSource>
@property (weak) IBOutlet NSTableView *tableView;
@property NSArray<NSString *> *tableViewData;
@end

@implementation TableViewController

- (id)init {
    if (self = [super initWithWindowNibName:[self className] owner:self]) {

        _tableViewData = @[@"NSColor.blackColor",
                           @"NSColor.controlTextColor",
                           @"NSColor.textColor",
                           @"NSColor.labelColor"];
    }
    return self;
}

- (void)windowDidLoad {
    [super windowDidLoad];

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

// MARK:- NSTableView Delegate
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return _tableViewData.count;
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    return _tableViewData[row];
}

// テーブルビューの内容表示前に呼ばれる
- (void)tableView:(NSTableView *)tableView
  willDisplayCell:(id)cell
   forTableColumn:(NSTableColumn *)tableColumn
              row:(NSInteger)row {
    [cell setTextColor:NSColor.blackColor];
    switch (row) {
        case 0:
            [cell setTextColor:NSColor.blackColor];
            break;
        case 1:
            [cell setTextColor:NSColor.controlTextColor];
            break;
        case 2:
            [cell setTextColor:NSColor.textColor];
            break;
        case 3:
            [cell setTextColor:NSColor.labelColor];
            break;
        default:
            break;
    }
}
@end