TableView Edit

本文详细介绍了iOS开发中Swift和Objective-C两种编程语言的应用技巧,包括语言特性、最佳实践和常见错误排查。通过实战案例,帮助开发者提升iOS应用开发效率。

//

// RootViewController.m


 

#import "RootViewController.h"

 

@interfaceRootViewController()<UITableViewDelegate,UITableViewDataSource>

 

@property (nonatomic,strong)UITableView*tableView;

 

@property (nonatomic,strong)NSMutableArray*mArr;

@property(nonatomic,strong)NSMutableDictionary *mDic;

@property (nonatomic,strong)NSMutableDictionary*imageDic;

@property (nonatomic,strong)NSMutableArray*imageArr;

@end

 

@implementationRootViewController

 

- (void)viewDidLoad {

   [superviewDidLoad];

 

self.title = @"suprise";

   // 创建tableView

self.tableView = [[UITableViewalloc]initWithFrame:[UIScreenmainScreen].boundsstyle:UITableViewStylePlain];

   // 设置分割线颜色

self.tableView.separatorColor =[UIColorredColor];

   //设置分割线格式

self.tableView.separatorStyle =UITableViewCellSeparatorStyleSingleLine;

   //设置代理

self.tableView.dataSource = self;

self.tableView.delegate = self;

   //添加到试图上

   [self.viewaddSubview:self.tableView];

   // 给导航栏右边加一分编辑按钮,(编辑按钮是UIViewController自带的)

self.navigationItem.rightBarButtonItem =self.editButtonItem;

self.tableView.backgroundColor = [UIColorredColor];

   // 获取数据

   [selfgetDate];

 

self.tableView.rowHeight = 150;

 

 

}

     //  一、编辑的四步

  //1、进入编辑状态

// 2、确定哪些cell可以被编辑

// 3、确定编辑模式

// 4、完成编辑

 

// 1、点击右按钮触发的编辑方法(既可以添加删除,又可以移动)

- (void)setEditing:(BOOL)editinganimated:(BOOL)animated{

   [supersetEditing:editinganimated:animated];

   // 将tableView置为编辑模式下。

   [self.tableViewsetEditing:editinganimated:animated];

}

 

// 2、设置可以被编辑的cell

- (BOOL)tableView:(UITableView*)tableViewcanEditRowAtIndexPath:(NSIndexPath *)indexPath{

 

return YES;

}

 

// 3、设置编辑模式

-(UITableViewCellEditingStyle)tableView:(UITableView*)tableVieweditingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.section == 0) {

returnUITableViewCellEditingStyleInsert;

    }

returnUITableViewCellEditingStyleDelete;

}

 

  //4、完成编辑

- (void)tableView:(UITableView*)tableViewcommitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath*)indexPath{

     // 先操作数据,再操作UI(控件)

if (editingStyle ==UITableViewCellEditingStyleDelete){

       [self.mDic[self.mArr[indexPath.section]] removeObjectAtIndex:

indexPath.row];

       [self.imageDic[self.imageArr[indexPath.section]] removeObjectAtIndex:

indexPath.row];

if([self.mDic[self.mArr[indexPath.section]] count] == 0) {

           // 删除键值对

           [self.mDicremoveObjectForKey:self.mArr[indexPath.section]];

           [self.imageDicremoveObjectForKey:self.imageArr[indexPath.section]];

//            //删除分组

           [self.mArrremoveObjectAtIndex:indexPath.section];

           [self.imageArrremoveObjectAtIndex:indexPath.section];

           // 删除分区(删除控件)

           [tableViewdeleteSections:[NSIndexSetindexSetWithIndex:indexPath.section]withRowAnimation:UITableViewRowAnimationLeft];

       }

    }

//   else{

//       // 先操作数据

//       NSString *key = self.mArr[indexPath.section];

//       NSMutableArray *arr = self.mDic[key];

//       [arrinsertObject:@"布鲁克" atIndex:indexPath.row];

//       

////       NSString *key1 = self.imageArr[indexPath.section];

////       NSMutableArray *arr1 = self.imageDic[key1];

////       [arr1insertObject:[UIImageimageNamed:@"h2.jpeg"]atIndex:indexPath.row];

//

//        // 再操作UI

//       [tableViewinsertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationBottom];

//   }

       [self.tableViewreloadData];

}

 

 // 二、移动的三个步骤

 // 1、设置处于编辑状态

 // 2、设置哪些cell可以被编辑

 //3、编辑过程

 

//2、设置哪些cell可编辑(移动)

- (BOOL)tableView:(UITableView*)tableViewcanMoveRowAtIndexPath:(NSIndexPath *)indexPath{

if (indexPath.section == 0) {

return NO;

    }

return YES;

}

 

 // 3、移动过程

- (void)tableView:(UITableView*)tableViewmoveRowAtIndexPath:(NSIndexPath*)sourceIndexPathtoIndexPath:(NSIndexPath *)destinationIndexPath{

   //获取起始点数组

NSMutableArray *arrSource =self.mDic[self.mArr[sourceIndexPath.section]];

NSMutableArray *imageArrSource =self.imageDic[self.imageArr[sourceIndexPath.section]];

   // 获取终点数组

NSMutableArray *arrDesti =self.mDic[self.mArr[destinationIndexPath.section]];

NSMutableArray *imageArrDesti =self.imageDic[self.mArr[destinationIndexPath.section]];

 

   // 先将cell对应的数据用字符串存储

NSString *str =arrSource[sourceIndexPath.row];

NSString *strImage =imageArrSource[sourceIndexPath.row];

 

   // 删除数据

   [arrSourceremoveObject:arrSource[sourceIndexPath.row]];

   [imageArrSourceremoveObject:imageArrSource[sourceIndexPath.row]];

   //插入数据

   [arrDestiinsertObject:stratIndex:destinationIndexPath.row];

   [imageArrDestiinsertObject:strImageatIndex:destinationIndexPath.row];

 

if ([arrSource count] == 0) {

       // 删除空数组

       [self.mDicremoveObjectForKey:self.mArr[sourceIndexPath.section]];

       [self.imageDicremoveObjectForKey:self.imageArr[sourceIndexPath.section]];

       // 删除头标题

       [self.mArrremoveObjectAtIndex:sourceIndexPath.section];

       [self.imageArrremoveObjectAtIndex:sourceIndexPath.section];

       // 删除分区

       [tableViewdeleteSections:[NSIndexSetindexSetWithIndex:sourceIndexPath.section]withRowAnimation:UITableViewRowAnimationFade];

    }

 

 

     // 重新加载数据,刷新视图

   [self.tableViewreloadData];

 

//   // 刷新某个分区

//   [tableViewreloadSections:[NSIndexSetindexSetWithIndex:sourceIndexPath.section]withRowAnimation:UITableViewRowAnimationFade];

}

 

    // 限制跨区移动

- (NSIndexPath *)tableView:(UITableView*)tableViewtargetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath*)sourceIndexPathtoProposedIndexPath:(NSIndexPath*)proposedDestinationIndexPath{

 

if (sourceIndexPath.section !=proposedDestinationIndexPath.section) {

returnsourceIndexPath;

    }

returnproposedDestinationIndexPath;

}

 

 

        // 设置分区个数

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{

return [self.mArr count];

}

       // 设置分区行数

- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{

return [self.mDic[self.mArr[section]]count];

}

 

 

- (UITableViewCell *)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath{

 

UITableViewCell *cell =[tableViewdequeueReusableCellWithIdentifier:@"reuse"];

if (cell == nil) {

cell =[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:@"reuse"];

    }

 

UIImage *image =[UIImageimageNamed:self.imageDic[self.imageArr[indexPath.section]][indexPath.row]];

cell.imageView.image = image;

 

cell.textLabel.text =self.mDic[self.mArr[indexPath.section]][indexPath.row];

 

return cell;

}

         // 设置头标题

- (NSString *)tableView:(UITableView*)tableViewtitleForHeaderInSection:(NSInteger)section{

returnself.mArr[section];

}

 

 

 

- (void)getDate{

   // 一个字典含有三个数组(对应三个分区)

   // 将key值作为分区头标题(字典与数组可变)

 

NSMutableArray *mArr1 =[NSMutableArrayarrayWithObjects:@"路飞",@"索隆",@"香吉士",nil];

NSMutableArray *mArr2 =[NSMutableArrayarrayWithObjects:@"乌索普", @"乔巴",@"弗兰奇",nil];

NSMutableArray *mArr3 =[NSMutableArrayarrayWithObjects:@"娜美",@"罗宾",nil];

self.mDic = [NSMutableDictionarydictionaryWithObjectsAndKeys:mArr1,@"A",mArr2,@"B",mArr3,@"C",nil];

self.mArr =[NSMutableArrayarrayWithObjects:@"A",@"B",@"C",nil];

 

NSMutableArray *imageArr1 =[NSMutableArrayarrayWithObjects:@"h4.jpeg",@"h2.jpeg",@"h6.jpeg",nil];

NSMutableArray *imageArr2 =[NSMutableArrayarrayWithObjects:@"h3.jpeg",@"h7.jpeg",@"h8.jpeg",nil];

NSMutableArray *imageArr3 =[NSMutableArrayarrayWithObjects:@"h5.jpeg",@"h1.jpeg",nil];

self.imageDic = [NSMutableDictionarydictionaryWithObjectsAndKeys:imageArr1,@"A",imageArr2,@"B",imageArr3,@"C",nil];

self.imageArr =[NSMutableArrayarrayWithObjects:@"A",@"B",@"C",nil];

 

}

 

- (UIView *)tableView:(UITableView*)tableViewviewForHeaderInSection:(NSInteger)section{

 

UILabel *label =[[UILabelalloc]initWithFrame:CGRectMake(130,0,40,30)];

label.text = self.mArr[section];

label.backgroundColor = [UIColorredColor];

UIView *view = [[UIViewalloc]init];

view.backgroundColor =[UIColoryellowColor];

   [viewaddSubview:label];

 

return view;

}

 

 

@end

 

以下是使用MySQL和TableView的示例代码,可以实现表格设置、排序、数据行数统计、分页、删除、添加和修改等功能: ```python # 导入必要的模块 from PyQt5.QtSql import QSqlDatabase, QSqlTableModel from PyQt5.QtWidgets import QMessageBox, QTableView, QHeaderView, QAbstractItemView, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QLabel class TableView(QWidget): def __init__(self): super().__init__() # 初始化数据库连接 db = QSqlDatabase.addDatabase("QMYSQL") db.setHostName("47.101.128.140") db.setDatabaseName("mydatabase") db.setUserName("test1") db.setPassword("test1") if not db.open(): QMessageBox.warning(self, "连接提示", "连接失败") return # 创建一个模型对象 self.model = QSqlTableModel() self.model.setTable("student") # 操作的是student这张表 self.model.select() # 查询所有数据 # 创建一个TableView对象 self.table_view = QTableView() self.table_view.setModel(self.model) # 将模型与TableView关联起来 self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows) # 设置选择行为,以行为单位 self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) # 设置选择模式,单选 self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 设置列宽自适应 self.table_view.verticalHeader().setVisible(False) # 隐藏行表头 # 创建一个水平布局 h_layout = QHBoxLayout() h_layout.addWidget(self.table_view) # 创建一个垂直布局 v_layout = QVBoxLayout() v_layout.addLayout(h_layout) # 创建一个标签和文本框,用于输入页码 self.page_label = QLabel("第1页") self.page_edit = QLineEdit() self.page_edit.setFixedWidth(50) self.page_edit.setText("1") self.page_edit.returnPressed.connect(self.goto_page) # 绑定回车事件 # 创建四个按钮,用于跳转到第一页、上一页、下一页、最后一页 self.first_button = QPushButton("第一页") self.first_button.clicked.connect(self.goto_first_page) self.prev_button = QPushButton("上一页") self.prev_button.clicked.connect(self.goto_prev_page) self.next_button = QPushButton("下一页") self.next_button.clicked.connect(self.goto_next_page) self.last_button = QPushButton("最后一页") self.last_button.clicked.connect(self.goto_last_page) # 创建一个水平布局,将标签、文本框和四个按钮添加到其中 page_layout = QHBoxLayout() page_layout.addWidget(self.page_label) page_layout.addWidget(self.page_edit) page_layout.addWidget(self.first_button) page_layout.addWidget(self.prev_button) page_layout.addWidget(self.next_button) page_layout.addWidget(self.last_button) # 创建一个按钮,用于添加一行数据 self.add_button = QPushButton("添加") self.add_button.clicked.connect(self.add_row) # 创建一个按钮,用于删除选定行 self.del_button = QPushButton("删除") self.del_button.clicked.connect(self.del_row) # 创建一个水平布局,将添加按钮和删除按钮添加到其中 button_layout = QHBoxLayout() button_layout.addWidget(self.add_button) button_layout.addWidget(self.del_button) # 创建一个垂直布局,将页码布局、按钮布局和TableView添加到其中 v_layout.addLayout(page_layout) v_layout.addLayout(button_layout) self.setLayout(v_layout) # 跳转到指定页 def goto_page(self): page = int(self.page_edit.text()) if page < 1: page = 1 elif page > self.model.rowCount() / 10 + 1: page = int(self.model.rowCount() / 10 + 1) self.page_edit.setText(str(page)) self.page_label.setText("第%d页" % page) self.model.setLimit(10) self.model.setOffset((page - 1) * 10) self.model.select() # 跳转到第一页 def goto_first_page(self): self.page_edit.setText("1") self.goto_page() # 跳转到上一页 def goto_prev_page(self): page = int(self.page_edit.text()) if page > 1: page -= 1 self.page_edit.setText(str(page)) self.goto_page() # 跳转到下一页 def goto_next_page(self): page = int(self.page_edit.text()) if page < self.model.rowCount() / 10 + 1: page += 1 self.page_edit.setText(str(page)) self.goto_page() # 跳转到最后一页 def goto_last_page(self): page = int(self.model.rowCount() / 10 + 1) self.page_edit.setText(str(page)) self.goto_page() # 添加一行数据 def add_row(self): row = self.model.rowCount() self.model.insertRow(row) # 删除选定行 def del_row(self): rows = self.table_view.selectionModel().selectedRows() for row in rows: self.model.removeRow(row.row()) self.model.select() # 创建一个TableView对象并显示 table_view = TableView() table_view.show() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值