Ios development-UI-UITableView and a small instance, ios-ui-uitableview

Source: Internet
Author: User

Ios development-UI-UITableView and a small instance, ios-ui-uitableview

[Note] reprinted, please indicate the source of blog Park-eat Tang sick Wukong http://www.cnblogs.com/hukezhu/

In IOS, the most common way to implement table display is to use UITableView.

@interface UITableView : UIScrollView <NSCoding>

UITableView is inherited from UIScrollView, so vertical scrolling is supported and the performance is excellent (this will be mentioned later, and cell reuse is supported)

  UITableView has two styles: grouping and not grouping.

GROUP: UITableViewStyleGrouped

Ungroup: UITableViewStylePlain

  

@property (nonatomic, readonly) UITableViewStyle           style;@property (nonatomic, assign)   id <UITableViewDataSource> dataSource;@property (nonatomic, assign)   id <UITableViewDelegate>   delegate;@property (nonatomic)          CGFloat                     rowHeight;            // will return the default value if unset
How to display data

1. UITableView requires a data source to display data (such as the above Code)

2. UITableView queries the total number of rows of data and what data is displayed for each row from the data source.

    

@protocol UITableViewDataSource<NSObject>@required- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;@optional- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;              // Default is 1 if not implemented- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;    // fixed font style. use custom view (UILabel) if you want something different- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;// Editing// Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;// Moving/reordering// Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;// Index- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;                                                    // return list of section titles to display in section index view (e.g. "ABCD...Z#")- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;  // tell table which section corresponds to section title/index (e.g. "B",1))// Data manipulation - insert and delete support// After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change// Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;// Data manipulation - reorder / moving support- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;@end

3. UITableView with no data element set is just an empty shell and no data is displayed.

4. The above code is the UITableViewDataSource protocol. All OC objects that comply with the UITableViewDataSource protocol can be the UITableView data source. Here we generally select the Controller as the data source.

So to sum upHow to Use UITableView to display data:

    • Complies with the UITableViewDataSource Protocol
    • Set the data source whose controller is UITableView (the controller is assumed here)
    • How to implement data sources

  

 

Required methods in UITableViewDataSource protocol:

  

@ Required // The number of rows in each group-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section; // Row display. implementers shocould * always * try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with outputs: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) // What content is displayed for each row-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath;

  

The following method does not have to be implemented. If this method is not implemented, the default group is 1.

// The total number of groups-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView; // This method is not required. If it is not implemented, it is a group by default.

 

The following is a small example to demonstrate the use of UITableView.

  

 

Is the application code structure and plist file:

  

The plist file here is more complex than the one described in the previous article. The dictionary contains a dictionary, so the dictionary-to-model conversion method used is different from the previous one. first, we need to convert the dictionary into a model and then the external dictionary.

The KZCar marked in is a car data model.

The KZCarGroup marked in is the data model of the vehicle group. The code is attached below. Pay special attention to the conversion process of this complex data model.

KZCar. h

1 // 2 // KZCar. h 3 // UI basics-06-05-19 4 // 5 // Created by hukezhu on 15/5/20. 6 // 7 // 8 9 # import <Foundation/Foundation. h> 10 11 @ interface KZCar: NSObject12 13/** 14 * declare image attributes 15 */16 @ property (nonatomic, copy) NSString * icon; 17 18/** 19 * declare name attribute 20 */21 @ property (nonatomic, copy) NSString * name; 22 23 24-(instancetype) initWithDict :( NSDictionary *) dict; 25 26 + (instancetype) carWithDict :( NSDictionary *) dict; 27 28 + (NSArray *) carsWithDict :( NSArray *) dictarray; 29 @ end

KZCar. m

1 // 2 // KZCar. m 3 // UI basics-06-05-19 4 // 5 // Created by hukezhu on 15/5/20. 6 // 7 // 8 9 # import "KZCar. h "10 11 @ implementation KZCar12 13-(instancetype) initWithDict :( NSDictionary *) dict {14 15 if (self = [super init]) {16 // use KVC17 [self setValuesForKeysWithDictionary: dict]; 18} 19 return self; 20} 21 22 23 + (instancetype) carWithDict :( NSDictionary *) dict {24 25 return [[self alloc] initWithDict: dict]; 26} 27 28 // here is the car data model. when analyzing the car array conversion, we found that we only need to input an array to 29 + (NSArray *) carsWithDict :( NSArray *) dictarray {30 31 32 NSMutableArray * tempArray = [NSMutableArray array]; 33 for (NSDictionary * dict in dictarray) {34 KZCar * car = [KZCar carWithDict: dict]; 35 [tempArray addObject: car]; 36} 37 return tempArray; 38} 39 @ end

 

KZCarGroup.h
//// KZCarGroup. h // UI basics-06-05-19 // Created by hukezhu on 15/5/20. //// # import <Foundation/Foundation. h> @ interface KZCarGroup: NSObject/*** declares the attributes of a car */@ property (nonatomic, strong) NSArray * cars; /*** declare the attribute of a title */@ property (nonatomic, copy) NSString * title;-(instancetype) initWithDict :( NSDictionary *) dict; + (instancetype) carGroupWithDict :( NSDictionary *) dict; + (NSArray *) carGroups; @ end
KZCarGroup.m
1 // 2 // KZCarGroup. m 3 // UI basics-06-05-19 4 // 5 // Created by hukezhu on 15/5/20. 6 // 7 // 8 9 # import "KZCarGroup. h "10 # import" KZCar. h "11 12 @ implementation KZCarGroup13-(instancetype) initWithDict :( NSDictionary *) dict {14 15 if (self = [super init]) {16 _ title = dict [@ "title"]; 17 18 // retrieve the array cars in the dictionary 19 NSArray * array = dict [@ "cars"]; 20 _ cars = [KZCar carsWithDict: array]; 21} 22 return self; 23} 24 25 + (instancetype) carGroupWithDict :( NSDictionary *) dict {26 27 return [[self alloc] initWithDict: dict]; 28} 29 30 + (NSArray *) carGroups {31 32 33 NSString * path = [[NSBundle mainBundle] pathForResource: @ "cars_total" ofType: @ "plist"]; 34 NSArray * dictArray = [NSArray arrayWithContentsOfFile: path]; 35 36 NSMutableArray * tempArray = [NSMutableArray array]; 37 for (NSDictionary * dict in dictArray) {38 KZCarGroup * carGroup = [KZCarGroup carGroupWithDict: dict]; 39 [tempArray addObject: carGroup]; 40} 41 return tempArray; 42} 43 @ end
 

 

ViewController. m

1 // 2 // ViewController. m 3 // 05-car multi-data 4 // 5 // Created by hukezhu on 15/5/20. 6 // 7 8 9 10 11 # import "ViewController. h "12 # import" KZCarGroup. h "13 # import" KZCar. h "14 15 @ interface ViewController () <UITableViewDataSource> 16 17 @ property (weak, nonatomic) IBOutlet UITableView * tableView; 18 19 20 21 @ property (nonatomic, strong) NSArray * cars; 22 @ end 23 24 @ implementation ViewController 25 26-(void) viewDidLoad {27 [super viewDidLoad]; 28 29 self. tableView. dataSource = self; 30 NSLog (@ "% @", self. cars); 31 32} 33 # pragma mark-Data Source Method 34/** 35 * returns a total of 36 37 */38-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView {39 40 return self. cars. count; 41} 42 43/** 44 * returns the number of rows in each group 45*46 */47-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {48 49 KZCarGroup * carGroup = self. cars [section]; 50 return carGroup. cars. count; 51} 52 53/** 54 * what data is displayed in each row? 55*56 */57-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {58 59 NSString * identity = @ "yes"; 60 UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: identity]; 61 62 if (cell = nil) {63 cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: identity]; 64} 65 // retrieve group model 66 KZCarGroup * carGroup = self. cars [indexPath. section]; 67 // extract the row model 68 KZCar * car = carGroup. cars [indexPath. row]; 69 70 cell. imageView. image = [UIImage imageNamed: car. icon]; 71 cell. textLabel. text = car. name; 72 return cell; 73} 74 75 76/** 77 * set the header biaoti 78*79 */80-(NSString *) tableView :( UITableView *) tableView titleForHeaderInSection :( NSInteger) section {81 82 // retrieve group model 83 KZCarGroup * carGroup = self. cars [section]; 84 return carGroup. title; 85 86} 87 88/** 89 * set the tail description 90*91 */92-(NSString *) tableView :( UITableView *) tableView titleForFooterInSection :( NSInteger) section {93 94 // retrieve the group model 95 KZCarGroup * carGroup = self. cars [section]; 96 return carGroup. title; 97 98} 99/** 100 * lazy loading data 101*102 */103-(NSArray *) cars {104 105 if (_ cars = nil) {106 _ cars = [KZCarGroup carGroups]; 107} 108 return _ cars; 109} 110 @ end

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.