码迷,mamicode.com
首页 > 其他好文 > 详细

UITableView

时间:2016-02-23 20:40:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

UITableView

  • 简单使用
    1. 遵守数据源协议和代理协议,创建tableView,指定数据源和代理
1.     //创建一个 TabView
2. UITableView *tabView = [[UITableView alloc] initWithFrame:self.view.bounds
3. style:UITableViewStylePlain];
4.
5. tabView.dataSource = self;
6. tabView.delegate = self;
7. [self.view addSubview:tabView];
  1. 实现数据源协议方法
1.#pragma mark DataSource
2.-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
3. return 1;
4.}
5.
6.-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
7. return _dataArray.count;
8.}
9.
10.-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
11. UITableViewCell *cell;
12.
13.
14. //从tabView中找到可重用的单元格,即创建了足够显示的单元格,那么就不用再创建新的单元格而重用已有的单元格
15.// cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
16. cell = [tableView cellForRowAtIndexPath:indexPath];// 作用同上
17. if (!cell) {
18. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
19. reuseIdentifier:@"cell"];
20.
21. }
22. cell.textLabel.text = _dataArray[indexPath.row];
23. cell.detailTextLabel.text = @"haha"; // 要用detailTextLable 样式 不是默认样式(default)才可用..
24. cell.imageView.image = [UIImage imageNamed:@"me.png"];
25. tableView.rowHeight = 100;//设置行高
26. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//最后有个箭头
27.
28. // 设置右侧视图为自定义视图,那么accessoryType将没有用了
29. UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
30. btn.frame = CGRectMake(0, 0, 80, 30);
31. [btn setTitle:@"download" forState:UIControlStateNormal];
32.// cell.accessoryView = btn;
33.
34. return cell;
35.}
  1. 实现代理方法
1.#pragma mark Delegate
2.
3.// 选中单元格的回调
4.-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
5.
6.// self.title = _dataArray[indexPath.row];
7. // 选中就打钩
8. isChecked[indexPath.row] = !isChecked[indexPath.row];
9. if (isChecked[indexPath.row]) {
10. [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; // 勾
11. }else{
12. [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryDisclosureIndicator;
13. }
14.
15.}

技术分享
由于选中状态没有在返回cell的数据源方法中和数据绑定在一起,所以选中后滚动出视图再滚回来就没有选中了

  • cell的简单介绍
    1.主要属性
1.@property (nonatomic, readonly, strong, nullable) UIImageView *imageView NS_AVAILABLE_IOS(3_0);  
2.
3.@property (nonatomic, readonly, strong, nullable) UILabel *textLabel NS_AVAILABLE_IOS(3_0);
4.
5.@property (nonatomic, readonly, strong, nullable) UILabel *detailTextLabel NS_AVAILABLE_IOS(3_0);
6.
7.@property (nonatomic) UITableViewCellAccessoryType accessoryType;
8.
9.@property (nonatomic, strong, nullable) UIView *accessoryView;
10.
11.@property (nonatomic) UITableViewCellAccessoryType editingAccessoryType;
12.
13.@property (nonatomic, strong, nullable) UIView *editingAccessoryView;
14.
15.@property (nonatomic) UITableViewCellSelectionStyle selectionStyle;

2.accessoryType是一个结构体常量有如下几种类型及其对应对样式:

UITableViewCellAccessoryType样式
UITableViewCellAccessoryNone 技术分享
UITableViewCellAccessoryDisclosureIndicator 技术分享
UITableViewCellAccessoryDetailDisclosureButton 技术分享
UITableViewCellAccessoryCheckmark 技术分享
UITableViewCellAccessoryDetailButton 技术分享

3.accessoryView即为cell右侧的视图,如果accessoryView != nil,那么设置accessoryType将没有作用

1.    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
2. btn.frame = CGRectMake(0, 0, 80, 30);
3. [btn setTitle:@"download" forState:UIControlStateNormal];
4. cell.accessoryView = btn;

技术分享
4.编辑模式,需要将tableview的editing 设置为 yes或者[tableView setEditing:YES animated:YES]; 才能进行编辑。

编辑模式下,用户可以进行删除、多选、重排序等操作。要进行多选操作必须将tableView.allowsMultipleSelectionDuringEditing = YES;在进行删除或重排序的时候必须对数据进行操作后才更新视图。

1.#import "ViewController.h"
2.#import "CDMyGroup.h"
3.#import "CDMyItem.h"
4.
5.
6.#define BARBUTTONITEM(TITLE,SEL) [[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SEL];
7.
8.#define WIDTH self.view.bounds.size.width
9.#define HEIGHT self.view.bounds.size.height
10.
11.@interface ViewController () <UITableViewDataSource, UITableViewDelegate> {
12. UITableView *myTableView;
13.
14. NSMutableArray *dataArray;
15.
16. UIRefreshControl *freshControl;
17.}
18.
19.@end
20.
21.@implementation ViewController
22.
23.- (void)viewDidLoad {
24. [super viewDidLoad];
25. // Do any additional setup after loading the view, typically from a nib.
26.
27. myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
28.
29. myTableView.dataSource = self;
30. myTableView.delegate = self;
31.
32.// [self createDataModel];
33. myTableView.allowsMultipleSelectionDuringEditing = YES; // 在编辑时多选
34. [self.view addSubview:myTableView];
35. freshControl = [[UIRefreshControl alloc] init];//下拉刷新
36. [freshControl addTarget:self action:@selector(fresh:)
37. forControlEvents:UIControlEventValueChanged];
38. [freshControl setTintColor:[UIColor orangeColor]];
39. [myTableView addSubview:freshControl];
40. [self customizeNavigationItem];
41.}
42.
43.-(void)fresh:(UIRefreshControl *)sender{
44. [dataArray removeAllObjects];
45. [self createDataModel];
46. [myTableView reloadData];
47. [sender endRefreshing];
48.}
49.
50.- (void) createDataModel {
51. if (!dataArray) {
52. dataArray = [NSMutableArray array];
53. }
54.
55. NSArray *names = @[@"圣斗士", @"海贼", @"火影忍者", @"美女"];
56. for (int i = 0; i < names.count; i++) {
57. CDMyGroup *group = [[CDMyGroup alloc] initWithName:names[i]];
58. [group loadItemsFromFile:[NSString stringWithFormat:@"%@.plist", names[i]]];
59. [dataArray addObject:group];
60. }
61.}
62.
63.#pragma mark UITableViewDataSource回调
64.
65.- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
66. return dataArray.count;
67.}
68.
69.- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
70. CDMyGroup *group = (id)dataArray[section];
71. return group.size;
72.}
73.
74.- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
75. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
76. if (!cell) {
77. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"CELL"];
78. }
79.
80. CDMyGroup *group = (id)dataArray[indexPath.section];
81. CDMyItem *item = group.items[indexPath.row];
82.
83. NSString *filePath = [[NSBundle mainBundle] pathForResource:item.imageName ofType:nil];
84. cell.textLabel.text = item.imageInfo;
85. cell.detailTextLabel.text = item.imageName;
86. cell.imageView.image = [UIImage imageWithContentsOfFile:filePath];
87. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
88.
89. return cell;
90.}
91.
92.- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
93. CDMyGroup *group = dataArray[section];
94. return group.name;
95.}
96.
97.// 编辑的回调
98.-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
99.
100. switch (editingStyle) {
101. case UITableViewCellEditingStyleDelete:{
102. // 删模型,再删视图
103. CDMyGroup *group = (CDMyGroup *)dataArray[indexPath.section];
104. [group removeItemAtIndex:indexPath.row];
105.
106. [myTableView deleteRowsAtIndexPaths:@[indexPath]
107. withRowAnimation:UITableViewRowAnimationLeft];
108. }
109. break;
110. case UITableViewCellEditingStyleInsert:
111. break;
112. case UITableViewCellEditingStyleNone:
113. break;
114. default:
115. break;
116. }
117.
118.}
119.
120.// 移动行(重排序)
121.-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
122.
123. CDMyGroup *sourceGroup = dataArray[sourceIndexPath.section];
124. CDMyGroup *destinationGroup = dataArray[destinationIndexPath.section];
125. if (sourceGroup == destinationGroup) {
126. [sourceGroup moveItemAtIndex:sourceIndexPath.row toIndex:destinationIndexPath.row];
127. }else{
128. CDMyItem *item = sourceGroup.items[sourceIndexPath.row];
129. [sourceGroup.items removeObject:item];
130. [destinationGroup.items insertObject:item atIndex:destinationIndexPath.row];
131. }
132.
133.}
134.
135.
136.#pragma mark UITableViewDelegate回调
137.
138.- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
139. return 150;
140.}
141.
142.// 自定义组头
143.- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
144. CDMyGroup *group = (id)dataArray[section];
145.
146. UIButton *sectionHeaderButton = [UIButton buttonWithType:UIButtonTypeCustom];
147. sectionHeaderButton.tag = 500 + section;
148. [sectionHeaderButton setBackgroundColor:group.color];
149. [sectionHeaderButton setTitle:group.name forState:UIControlStateNormal];
150. [sectionHeaderButton addTarget:self action:@selector(sectionHeaderButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
151.
152. return sectionHeaderButton;
153.}
154.
155.#pragma mark 其他事件的回调方法
156.//组头的点击回调
157.- (void) sectionHeaderButtonClicked:(UIButton *) sender {
158. CDMyGroup *group = (id)dataArray[sender.tag - 500];
159. group.folded = !group.isFolded;
160. [myTableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag - 500] withRowAnimation:UITableViewRowAnimationTop];
161.}
162.
163.-(void)editRow:(UIBarButtonItem *)sender{
164. if ([myTableView isEditing]) {
165. [myTableView setEditing:NO animated:YES];
166.// self.navigationItem.leftBarButtonItem.title = @"编辑";
167. UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[1];
168. item.title = @"编辑";
169. }else{
170. [myTableView setEditing:YES animated:YES];
171.// self.navigationItem.leftBarButtonItem.title = @"完成";
172. UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[1];
173. item.title = @"完成";
174. }
175.}
176.
177.-(void)addRow:(UIBarButtonItem *)sender{
178. CDMyItem *item = [[CDMyItem alloc] init];
179. item.imageInfo = @"yeah";
180. item.imageName = @"火影01.png";
181.
182. NSInteger section = 0;
183. for (CDMyGroup *group in dataArray) {
184. if (group.folded) {
185. section++;
186. }else{
187. [group insertItem:item atIndex:group.size];
188. [myTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:group.size - 1 inSection:section]]
189. withRowAnimation:UITableViewRowAnimationRight];
190. break;
191. }
192. }
193.}
194.// 多选删除
195.-(void)deleteRows:(UIBarButtonItem *)sender{
196. NSMutableArray *indexs = [[myTableView indexPathsForSelectedRows] mutableCopy];// 选中的行
197. [indexs sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
198. NSIndexPath *indexPath1 = obj1;
199. NSIndexPath *indexPath2 = obj2;
200.// if (indexPath1.section == indexPath2.section) {
201.// if (indexPath1.row < indexPath2.row) {
202.// return NSOrderedDescending;
203.// }else{
204.// return NSOrderedAscending;
205.// }
206.// }else if (indexPath1.section < indexPath2.section) {
207.// return NSOrderedDescending;
208.// }else{
209.// return NSOrderedAscending;
210.// }
211.
212. return indexPath1.section == indexPath2.section ? indexPath1.row < indexPath2.row : indexPath1.section < indexPath2.section;
213.
214. }];
215. for (NSIndexPath *indexPath in indexs) {
216. [((CDMyGroup *)dataArray[indexPath.section]).items removeObjectAtIndex:indexPath.row];
217. }
218. [myTableView deleteRowsAtIndexPaths:indexs withRowAnimation:YES];
219.}
220.
221.#pragma mark 定制导航栏
222.-(void)customizeNavigationItem{
223.// self.navigationItem.leftBarButtonItem = BARBUTTONITEM(@"编辑",@selector(editRow:));
224.// [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editRow:)];
225. UIBarButtonItem *item1 = BARBUTTONITEM(@"删除", @selector(deleteRows:));
226. UIBarButtonItem *item2 = BARBUTTONITEM(@"编辑",@selector(editRow:));
227. self.navigationItem.leftBarButtonItems = @[item1,item2];
228.
229. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(addRow:)];
230.}

技术分享

  1. 自定义组头
1.- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;   
2.
3.- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
  1. 更改删除时掉样式
1.// 删除按钮的文字
2.-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
3. return @"删除";
4.}
5.
6./**替代上面的方法*/
7.- ( NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
8. /**
9. * style 为default时,删除按钮时红色的;
10. * style 为normal时,删除按钮呈现灰色
11. */

12. UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
13.
14. NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:favoriteArray];
15. NSMutableArray *tmpDeleteArray = [NSMutableArray arrayWithArray:deleteArray];
16. [tmpDeleteArray addObject:[tmpArray objectAtIndex:indexPath.row]];
17. [tmpArray removeObjectAtIndex:indexPath.row];
18. favoriteArray = tmpArray;
19. deleteArray = tmpDeleteArray;
20.
21. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
22.
23. [favoriteTableView reloadData];
24. }];
25.
26. return @[deleteAction];
27.}
28.

技术分享

  1. 分组和索引
1.// 组名
2.-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
3. NSInteger index = [leftIndex integerValue];
4. NSString *str = nil;
5. if (index != 5) {
6. if ([grounp[index] isKindOfClass:[NSDictionary class]]) {
7. NSDictionary *dic = grounp[index];
8. NSArray *keys = [dic allKeys];
9. NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
10. keys = [keys sortedArrayUsingDescriptors:@[descriptor]];
11. NSString *key = keys[section];
12. str = key;
13. }
14. }
15.
16. return str;
17.}
18.// 索引
19.- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
20. NSInteger index = [leftIndex integerValue];
21. NSArray *resArray = nil;
22. if (index != 5) {
23. if ([grounp[index] isKindOfClass:[NSDictionary class]]) {
24. NSDictionary *dic = grounp[index];
25. NSArray *keys = [dic allKeys];
26. NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
27. keys = [keys sortedArrayUsingDescriptors:@[descriptor]];
28. resArray = keys;
29. }
30. }
31. return resArray;
32.}

技术分享

 

UITableView

标签:

原文地址:http://www.cnblogs.com/buakaw/p/5210941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!