NSTableView和UITableView的使用上有些不同,步驟比較繁瑣
#import "ViewController.h"
@interface ViewController ()<NSTableViewDataSource,NSTableViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1.0.創(chuàng)建卷軸視圖
NSScrollView *scrollView = [[NSScrollView alloc] init];
// 1.1.有(顯示)垂直滾動條
scrollView.hasVerticalScroller = YES;
// 1.2.設(shè)置frame并自動布局
scrollView.frame = self.view.bounds;
scrollView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
// 1.3.添加到self.view
[self.view addSubview:scrollView];
// 2.0.創(chuàng)建表視圖
NSTableView *tableView = [[NSTableView alloc] init];
tableView.frame = self.view.bounds;
// 2.1.設(shè)置代理和數(shù)據(jù)源
tableView.delegate = self;
tableView.dataSource = self;
// 2.2.設(shè)置為ScrollView的documentView
scrollView.contentView.documentView = tableView;
// 3.0.創(chuàng)建表列
NSTableColumn *columen1 = [[NSTableColumn alloc] initWithIdentifier:@"columen1"];
// 3.1.設(shè)置最小的寬度
columen1.minWidth = 150.0;
// 3.2.允許用戶調(diào)整寬度
columen1.resizingMask = NSTableColumnUserResizingMask;
// 3.3.添加到表視圖
[tableView addTableColumn:columen1];
// 4.0.同理,表列都是這么創(chuàng)建的
NSTableColumn *columen2 = [[NSTableColumn alloc] initWithIdentifier:@"columen2"];
columen2.minWidth = 150.0;
columen2.resizingMask = NSTableColumnAutoresizingMask | NSTableColumnUserResizingMask;
/*****
NSTableColumnNoResizing 不能改變寬度
NSTableColumnAutoresizingMask 拉大拉小窗口時會自動布局
NSTableColumnUserResizingMask 允許用戶調(diào)整寬度
***/
[tableView addTableColumn:columen2];
}
// 設(shè)置行數(shù)
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
return 15;
}
// 設(shè)置Cell
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
// 1.0.創(chuàng)建一個Cell
NSTextField *view = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 100, 30)];
view.bordered = NO;
view.editable = NO;
// 1.1.判斷是哪一列
if ([tableColumn.identifier isEqualToString:@"columen1"]) {
view.stringValue = [NSString stringWithFormat:@"第1列的第%ld個Cell",row + 1];
}else if ([tableColumn.identifier isEqualToString:@"columen2"]) {
view.stringValue = [NSString stringWithFormat:@"第2列的第%ld個Cell",row + 1];
}else {
view.stringValue = [NSString stringWithFormat:@"不知道哪列的第%ld個Cell",row + 1];
}
return view;
}
// 設(shè)置行高
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{
return 30;
}