mac 纯代码创建tableview

iOS和Mac OS的tableview使用略有不同

Mac OS的tableView需要一个Container来包裹它,才可以滑动,而iOS的不用
Mac OS的tableview里面多了一个概念叫做column(列),而iOS中没有这个概念
iOS中有section的概念,可是Mac OS中没有(NSCollectionView中有)

注释:如果Mac开发中需求必需使用section的话,可以去研究下NSCollectionView

Mac os的tableview在datasource做视图的时候,有两种情况:
1、View Based TableView
2、Cell Based TableView
这两种情况可用的delegate方法不太相同,需要注意,否则可能出现delegate方法不被调用的问题

@interface AppDelegate ()<NSTableViewDataSource,NSTableViewDelegate>
{
    NSScrollView *_tableContainerView;
    NSMutableArray *_dataSourceArray;

    NSTextField *_scrollTF;
    NSButton *_deleteBtn;
    NSButton *_addBtn;

    NSInteger _selectedRowNum;
}
@property (weak) IBOutlet NSWindow *window;
@property (nonatomic) NSTableView *tableView;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    //虚拟的dataSource
    _dataSourceArray = [[NSMutableArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];
    _selectedRowNum = -1;

    //删除按钮
    _deleteBtn = [[NSButton alloc] initWithFrame:CGRectMake(415, 250, 70, 25)];
    _deleteBtn.title = @"删除选中行";
    _deleteBtn.wantsLayer = YES;
    _deleteBtn.layer.cornerRadius = 3.0f;
    _deleteBtn.layer.borderColor = [NSColor lightGrayColor].CGColor;
    [_deleteBtn setTarget:self];
    _deleteBtn.action = @selector(deleteTheSelectedRow);
    [self.window.contentView addSubview:_deleteBtn];

    //添加按钮
    _addBtn = [[NSButton alloc] initWithFrame:CGRectMake(415, 170, 70, 25)];
    _addBtn.title = @"上面添一行";
    _addBtn.wantsLayer = YES;
    _addBtn.layer.cornerRadius = 3.0f;
    _addBtn.layer.borderColor = [NSColor lightGrayColor].CGColor;
    [_addBtn setTarget:self];
    _addBtn.action = @selector(addRowUnderTheSelectedRow);
    [self.window.contentView addSubview:_addBtn];

    //滚动显示的TF
    _scrollTF = [[NSTextField alloc] initWithFrame:CGRectMake(415, 90, 80, 15)];
    _scrollTF.stringValue = @"滚动 0.0";
    _scrollTF.font = [NSFont systemFontOfSize:15.0f];
    _scrollTF.textColor = [NSColor blackColor];
    _scrollTF.drawsBackground = NO;
    _scrollTF.bordered = NO;
    _scrollTF.focusRingType = NSFocusRingTypeNone;
    _scrollTF.editable = NO;
    [self.window.contentView addSubview:_scrollTF];

    //tableView
    _tableContainerView = [[NSScrollView alloc] initWithFrame:CGRectMake(0, 0, 400, 309)];
    _tableView = [[NSTableView alloc] initWithFrame:CGRectMake(0, 20,
                                                               _tableContainerView.frame.size.width-20,
                                                               _tableContainerView.frame.size.height)];
    [_tableView setBackgroundColor:[NSColor colorWithCalibratedRed:220.0/255 green:220.0/255 blue:220.0/255 alpha:1.0]];
    _tableView.focusRingType = NSFocusRingTypeNone;                             //tableview获得焦点时的风格
    _tableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleRegular;//行高亮的风格
    _tableView.headerView.frame = NSZeroRect;                                   //表头
    _tableView.delegate = self;
    _tableView.dataSource = self;

    // 第一列
    NSTableColumn * column1 = [[NSTableColumn alloc] initWithIdentifier:@"firstColumn"];
    [column1 setWidth:200];
    [_tableView addTableColumn:column1];//第一列

    // 第二列
    NSTableColumn * column2 = [[NSTableColumn alloc] initWithIdentifier:@"secondColumn"];
    [column2 setWidth:200];
    [_tableView addTableColumn:column2];//第二列

    [_tableContainerView setDocumentView:_tableView];
    [_tableContainerView setDrawsBackground:NO];        //不画背景(背景默认画成白色)
    [_tableContainerView setHasVerticalScroller:YES];   //有垂直滚动条
    //[_tableContainer setHasHorizontalScroller:YES];   //有水平滚动条
    _tableContainerView.autohidesScrollers = YES;       //自动隐藏滚动条(滚动的时候出现)
    [self.window.contentView addSubview:_tableContainerView];

    //监测tableview滚动
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(tableviewDidScroll:)
                                                name:NSViewBoundsDidChangeNotification
                                              object:[[_tableView enclosingScrollView] contentView]];
}
#pragma mark - NSTableViewDataSource,NSTableViewDelegate
#pragma mark -required methods
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    return _dataSourceArray.count;
}
//这个方法虽然不返回什么东西,但是必须实现,不实现可能会出问题-比如行视图显示不出来等。(10.11貌似不实现也可以,可是10.10及以下还是不行的)
- (nullable id)tableView:(NSTableView *)tableView objectValueForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row
{
    return nil;
}
#pragma mark -other methods
- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    return 58;
}
- (nullable NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row
{
    NSString *strIdt=[tableColumn identifier];
    NSTableCellView *aView = [tableView makeViewWithIdentifier:strIdt owner:self];
    if (!aView)
        aView = [[NSTableCellView alloc]initWithFrame:CGRectMake(0, 0, tableColumn.width, 58)];
    else
        for (NSView *view in aView.subviews)[view removeFromSuperview];

    NSTextField *textField = [[NSTextField alloc] initWithFrame:CGRectMake(15, 20, 156+50, 17)];
    textField.stringValue = [NSString stringWithFormat:@"%@-ºµº-%@",tableColumn.identifier,[_dataSourceArray objectAtIndex:row]];
    textField.font = [NSFont systemFontOfSize:15.0f];
    textField.textColor = [NSColor blackColor];
    textField.drawsBackground = NO;
    textField.bordered = NO;
    textField.focusRingType = NSFocusRingTypeNone;
    textField.editable = NO;
    [aView addSubview:textField];
    return aView;
}
- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row
{
//    NSLog(@"====%ld", (long)row);
    _selectedRowNum = row;
    return YES;
}

- (void)tableView:(NSTableView *)tableView didClickTableColumn:(NSTableColumn *)tableColumn{
    NSLog(@"%@", tableColumn.dataCell);
}
#pragma mark - tableview滚动处理
-(void)tableviewDidScroll:(NSNotification *)notification
{
    NSClipView *contentView = [notification object];
    CGFloat scrollY = contentView.visibleRect.origin.y-20;//这里减去20是因为tableHeader的20高度
    _scrollTF.stringValue = [NSString stringWithFormat:@"滚动 %.1f",scrollY];
}


#pragma mark - 删除&&添加某一行
-(void)deleteTheSelectedRow
{
    if (_selectedRowNum == -1) {NSLog(@"请先选择要删除的行"); return;}
    [_tableView beginUpdates];
    [_dataSourceArray removeObjectAtIndex:_selectedRowNum];
    [_tableView removeRowsAtIndexes:[NSIndexSet indexSetWithIndex:_selectedRowNum] withAnimation:NSTableViewAnimationSlideUp];
    [_tableView endUpdates];
    _selectedRowNum = -1;
}
-(void)addRowUnderTheSelectedRow
{
    if (_selectedRowNum == -1) {NSLog(@"请先选择要哪行上面添一行"); return;}
    NSString *seletedDataObject = [_dataSourceArray objectAtIndex:_selectedRowNum];
    NSString *addObject = [NSString stringWithFormat:@"%@+",seletedDataObject];

    [_tableView beginUpdates];
    [_dataSourceArray insertObject:addObject atIndex:_selectedRowNum];
    [_tableView insertRowsAtIndexes:[NSIndexSet indexSetWithIndex:_selectedRowNum] withAnimation:NSTableViewAnimationSlideDown];
    [_tableView endUpdates];
    _selectedRowNum++;
}
#pragma mark -
- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}
// 选中的响应
-(void)tableViewSelectionDidChange:(nonnull NSNotification* )notification{
    self.tableView = notification.object;
    //do something
    NSLog(@"-----%ld", (long)self.tableView.selectedRow);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
以下是一个简单的示例代码,演示如何实现 tableview 中的全部勾选检查框。 在ViewController.h文件中,添加以下属性和方法: ```objective-c @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) NSMutableArray *selectedArray; @property (nonatomic, assign) BOOL isAllSelected; - (void)selectAllRows:(id)sender; ``` 在ViewController.m文件中,实现以下代码: ```objective-c - (void)viewDidLoad { [super viewDidLoad]; // 初始化tableview self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; self.tableView.delegate = self; self.tableView.dataSource = self; [self.view addSubview:self.tableView]; // 初始化selectedArray self.selectedArray = [NSMutableArray array]; for (NSInteger i = 0; i < 10; i++) { [self.selectedArray addObject:@(NO)]; } // 添加“全选”按钮 UIBarButtonItem *selectAllButton = [[UIBarButtonItem alloc] initWithTitle:@"全选" style:UIBarButtonItemStylePlain target:self action:@selector(selectAllRows:)]; self.navigationItem.rightBarButtonItem = selectAllButton; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } // 添加勾选框 if (![cell.contentView viewWithTag:100]) { UIButton *selectButton = [UIButton buttonWithType:UIButtonTypeCustom]; selectButton.tag = 100; selectButton.frame = CGRectMake(10, 10, 30, 30); [selectButton setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal]; [selectButton setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected]; [selectButton addTarget:self action:@selector(selectRow:) forControlEvents:UIControlEventTouchUpInside]; [cell.contentView addSubview:selectButton]; } // 设置勾选框状态 UIButton *selectButton = [cell.contentView viewWithTag:100]; selectButton.selected = [self.selectedArray[indexPath.row] boolValue]; // 设置cell内容 cell.textLabel.text = [NSString stringWithFormat:@"第%ld行", indexPath.row+1]; return cell; } - (void)selectRow:(UIButton *)sender { // 获取点击的cell的indexPath UITableViewCell *cell = (UITableViewCell *)sender.superview.superview; NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; // 修改勾选状态 BOOL isSelected = [self.selectedArray[indexPath.row] boolValue]; isSelected = !isSelected; [self.selectedArray replaceObjectAtIndex:indexPath.row withObject:@(isSelected)]; // 更新勾选框状态 sender.selected = isSelected; // 判断是否全部勾选,更新“全选”按钮状态 NSInteger selectedCount = 0; for (NSNumber *isSelected in self.selectedArray) { if ([isSelected boolValue]) { selectedCount++; } } self.isAllSelected = (selectedCount == self.selectedArray.count); self.navigationItem.rightBarButtonItem.title = self.isAllSelected ? @"取消全选" : @"全选"; } - (void)selectAllRows:(id)sender { // 修改勾选状态 self.isAllSelected = !self.isAllSelected; for (NSInteger i = 0; i < self.selectedArray.count; i++) { [self.selectedArray replaceObjectAtIndex:i withObject:@(self.isAllSelected)]; } // 更新勾选框状态 [self.tableView reloadData]; // 更新“全选”按钮状态 self.navigationItem.rightBarButtonItem.title = self.isAllSelected ? @"取消全选" : @"全选"; } - (void)finishButtonClicked:(id)sender { // 遍历勾选状态进行操作 for (NSInteger i = 0; i < self.selectedArray.count; i++) { if ([self.selectedArray[i] boolValue]) { // 执行相应的操作 } } } ``` 以上代码实现了在 tableview 中添加全部勾选检查框的功能,通过点击勾选框来修改勾选状态,通过 “全选” 按钮来修改所有行的勾选状态。在点击完成按钮时,遍历所有行的勾选状态进行相应操作。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值