Basic usage and performance optimization method of UITableView control in IOS development _ios

Source: Internet
Author: User

UITableView Control Basic Use

De jure simple hero Show program

NJHero.h File Code (dictionary-turn model)

Copy Code code as follows:

#import <Foundation/Foundation.h>

@interface Njhero:nsobject
/**
* Avatar
*/
@property (nonatomic, copy) NSString *icon;
/**
* Name
*/
@property (nonatomic, copy) NSString *name;
/**
* Description
*/
@property (nonatomic, copy) NSString *intro;

-(Instancetype) Initwithdict: (Nsdictionary *) dict;
+ (Instancetype) herowithdict: (Nsdictionary *) dict;
@end

NJVIEWCONTROLLER.M File Code

#import "NJViewController.h"
#import "NJHero.h"

@interface Njviewcontroller () <uitableviewdatasource, uitableviewdelegate>
/**
* Save all the heroic data
*/
@property (nonatomic, strong) Nsarray *heros;
@property (Weak, nonatomic) Iboutlet UITableView *tableview;

@end




Copy Code code as follows:



@implementation Njviewcontroller

#pragma mark-Lazy load


-(Nsarray *) heros


{


if (_heros = = nil) {


1. Get full path


NSString *fullpath = [[NSBundle mainbundle] pathforresource:@ "heros" oftype:@ "plist"];


2. More full path loading data


Nsarray *dictarray = [Nsarray Arraywithcontentsoffile:fullpath];


3. Dictionary Turn model


Nsmutablearray *models = [Nsmutablearray arrayWithCapacity:dictArray.count];


For (Nsdictionary *dict in Dictarray) {


Njhero *hero = [Njhero herowithdict:dict];


[Models Addobject:hero];


}


4. Value Assignment Data


_heros = [models copy];


}


4. Return Data


return _heros;


}

-(void) viewdidload
{
[Super Viewdidload];
Set the height of the cell
Use attributes to set the height of the cell when the cell in each row is highly consistent
Self.tableView.rowHeight = 60;
Self.tableView.delegate = self;
}

#pragma mark-uitableviewdatasource


How many groups are returned


-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView


{


return 1;


}


Returns how many rows are in each group


-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section


{


return self.heros.count;


}


Returns which row of which group to display what content


-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath


{


1. Create a cell


UITableViewCell *cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle ReuseIdentifier:nil];


2. Set up data


2.1 Take out the corresponding row model


Njhero *hero = Self.heros[indexpath.row];


2.2 Assignment-corresponding data


Cell.textLabel.text = Hero.name;


Cell.detailTextLabel.text = Hero.intro;


Cell.imageView.image = [UIImage ImageNamed:hero.icon];


3. Return cell


return cell;


}


#pragma mark-uitableviewdelegate


/*


Use the proxy method to set the cell height when the cell height of each row is inconsistent


-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath


{


if (1 = indexpath.row) {


return 180;


}


Return 44;


}


*/

#pragma mark-Control whether the status bar is displayed
/**
* Return Yes to represent the hidden status bar, no instead
*/
-(BOOL) Prefersstatusbarhidden
{
return YES;
}
@end




Implementation effect:


Code Note points:

(1) in the Code of the dictionary model to use the following code, for the variable array of dictarray.count storage space, you can improve the performance of the program

Copy Code code as follows:

Nsmutablearray *models = [NSMutableArrayarrayWithCapacity:dictArray.count];



(2) Set the height of the cell

There are three ways to set the height of the cell

1 can be set in the initial load method, Self.tableView.rowHeight = 60; This applies to setting the cell height using attributes when each row of cell is highly consistent.

2) set in storyboard, suitable for highly consistent

3 when the cell height of each row is inconsistent, use the Proxy method to set the cell height

Copy Code code as follows:

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath

{

if (1 = indexpath.row) {

return 180;

}

Return 44;

}




Ii. Some properties of the cell

code example:

Copy Code code as follows:

#import "NJViewController.h"
#import "NJHero.h"

@interface Njviewcontroller () <uitableviewdatasource, uitableviewdelegate>
/**
* Save all the heroic data
*/
@property (nonatomic, strong) Nsarray *heros;
@property (Weak, nonatomic) Iboutlet UITableView *tableview;

@end




Copy Code code as follows:



@implementation Njviewcontroller

#pragma mark-Lazy load


-(Nsarray *) heros


{


if (_heros = = nil) {


1. Get full path


NSString *fullpath = [[NSBundle mainbundle] pathforresource:@ "heros" oftype:@ "plist"];


2. More full path loading data


Nsarray *dictarray = [Nsarray Arraywithcontentsoffile:fullpath];


3. Dictionary Turn model


Nsmutablearray *models = [Nsmutablearray arrayWithCapacity:dictArray.count];


For (Nsdictionary *dict in Dictarray) {


Njhero *hero = [Njhero herowithdict:dict];


[Models Addobject:hero];


}


4. Value Assignment Data


_heros = [models copy];


}


4. Return Data


return _heros;


}

-(void) viewdidload
{
[Super Viewdidload];
Set the height of the cell
Use attributes to set the height of the cell when the cell in each row is highly consistent
Self.tableView.rowHeight = 60;
Self.tableView.delegate = self;

}

#pragma mark-uitableviewdatasource


How many groups are returned


-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView


{


return 1;


}


Returns how many rows are in each group


-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section


{


return self.heros.count;


}


Returns which row of which group to display what content


-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath


{


1. Create a cell


UITableViewCell *cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle ReuseIdentifier:nil];


2. Set up data


2.1 Take out the corresponding row model


Njhero *hero = Self.heros[indexpath.row];


2.2 Assignment-corresponding data


Cell.textLabel.text = Hero.name;


Cell.detailTextLabel.text = Hero.intro;


Cell.imageView.image = [UIImage ImageNamed:hero.icon];





2.3 Set the secondary view of the cell


Cell.accessorytype = Uitableviewcellaccessorydisclosureindicator;


if (0 = indexpath.row) {


Cell.accessoryview = [UIButton buttonwithtype:uibuttontypecontactadd];


}else


{


Cell.accessoryview = [[Uiswitch alloc] init];


}


UIButton *btn = [[UIButton alloc] init];


Btn.backgroundcolor = [Uicolor Redcolor];


Cell.accessoryview = BTN;








2.4 Setting the background color of the cell


Cell.backgroundcolor = [Uicolor Bluecolor];





Setting the background of the default state


UIView *view = [[UIView alloc] init];


View.backgroundcolor = [Uicolor Bluecolor];


Cell.backgroundview = view;





Uiimageview *iv = [[Uiimageview alloc] initwithimage:[uiimage imagenamed:@ "Buttondelete"]];


Cell.backgroundview = IV;





Set the background of a selected state


UIView *view2 = [[UIView alloc] init];


View2.backgroundcolor = [Uicolor Purplecolor];


Cell.selectedbackgroundview = View2;


3. Return cell


return cell;


}


#pragma mark-Control whether the status bar is displayed
/**
* Return Yes to represent the hidden status bar, no instead
*/
-(BOOL) Prefersstatusbarhidden
{
return YES;
}
@end




Implementation effect:


Some properties of the cell:

(1) Set the auxiliary view of the cell, set the Cell.accessoryview (the system provides an enumerated type, or you can customize the @ parent class pointer to the subclass object);

(2) Set the background color of the cell, there are two ways to set the background color of the cell:

The background of the cell can be set through both BackgroundColor and Backgroundview. But the Backgroundview priority is higher than the backgroundcolor, so if BackgroundColor and Backgroundview are set at the same time, Then Backgroundview will cover backgroundcolor.

Example: Cell.backgroundcolor = [Uicolorbluecolor];

(3) Setting the background of the cell default state

Example 1:

Copy Code code as follows:

UIView *view = [[UIView alloc] init];

View.backgroundcolor = [Uicolor Bluecolor];

Cell.backgroundview = view;




Example 2:


Copy Code code as follows:

Uiimageview *iv = [[Uiimageviewalloc] initwithimage:[uiimageimagenamed:@ "Buttondelete"]];

Cell.backgroundview = IV (parent class pointer to child class object, you can use a picture to set the gorgeous effect with simple action)




(4) Set the background of the cell selected state

Example:

Copy Code code as follows:

UIView *view2 = [[UIView alloc] init];

View2.backgroundcolor = [Uicolorpurplecolor];

Cell.selectedbackgroundview = View2;




Iii. Some properties of TableView

code example:

Copy Code code as follows:



#import "NJViewController.h"

@interface Njviewcontroller () <UITableViewDataSource>

@end

@implementation Njviewcontroller

-(void) viewdidload
{
[Super Viewdidload];

1. Create TableView
UITableView *tableview = [[UITableView alloc] init];
Tableview.frame = Self.view.bounds;

2. Set up a data source
Tableview.datasource =self;

3. Add TableView to view
[Self.view Addsubview:tableview];

4. Set Split Line Style
Tableview.separatorstyle = Uitableviewcellseparatorstylenone;

5. Set the color of the split line
The received parameter is the proportional value of the color
Tableview.separatorcolor = [Uicolor colorwithred:0/255.0 green:255/255.0 blue:0/255.0 alpha:255/255.0];

Set the head view of TableView
Tableview.tableheaderview = [UIButton buttonwithtype:uibuttontypecontactadd];
Tableview.tablefooterview = [[Uiswitch alloc] init];
}

-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView
{
return 1;
}
-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section
{
return 10;
}

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath
{
1. Create a cell
UITableViewCell *cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault ReuseIdentifier:nil];

2. Set the cell data
Cell.textLabel.text = [NSString stringwithformat:@ "%d", Indexpath.row];

3. Return cell
return cell;
}

-(BOOL) Prefersstatusbarhidden
{
return YES;
}
@end




Implementation effect:


Some properties of TableView:

(1) Set the split style (Tableview.separatorstyle), which is an enumeration type

(2) Set the color of the split line, you can directly use the system given color, if the system given the color does not meet the requirements, can also be customized.

Add: The color is divided into 24-bit and 32-bit, as follows

24bit Color

R 8bit 0 ~ 255

G 8bit 0 ~ 255

B 8bit 0 ~ 255

32bit Color

A 8bit 0 ~ 255 (TOU)

R 8bit

G 8bit

B 8bit

#ff FF FF White

#00 00 00 Black

#ff 00 00 Red

#255 00 00

Set as an instance of the custom color:

Copy Code code as follows:
Tableview.separatorcolor = [uicolorcolorwithred:0/255.0green:255/255.0blue:0/255.0alpha:255/255.0];

The received parameter is the proportional value of the color




(3) Set top and bottom views


Copy Code code as follows:

Tableview.tableheaderview//Top

Tableview.tablefooterview//Bottom




Performance problems with UITableViewCell
First, some introduction of UITableViewCell

Each row of the UITableView is a uitableviewcell that initializes each ⼀ line by DataSource's Tableview:cellforrowatindexpath: Method

UITableViewCell has a default child view inside: Contentview,contentview is the parent view of what UITableViewCell displays, and can display some auxiliary instruction views

The auxiliary instruction view is ⽤ to display an icon representing the action, which can be displayed by setting the Accessorytype of the UITableViewCell, which is Uitableviewcellaccessorynone (without ⽰ show Auxiliary refers to ⽰ view), Other values are as follows:

Copy Code code as follows:

Uitableviewcellaccessorydisclosureindicator

Uitableviewcellaccessorydetaildisclosurebutton

Uitableviewcellaccessorycheckmark




You can also customize the secondary instruction view through the cell's Accessoryview property (⽐ such as a switch to the right)

Ii. issues

The work of the cell: how many items can be seen when the program executes, how many data it creates, and if the view scrolls then creates the newly displayed content. (called automatically by the system). That is, when a cell appears in the field of view, the creation of a cell is invoked. This logic doesn't seem to be a problem, but does it really matter?

When creating the call, we print the message using NSLog and print the address of the cell that was created. We find that if the amount of data is very large, the user scrolls back and forth within a short period of time, creates a lot of cell, opens up space, and if it's rolling back, by printing the address, we find that it doesn't reuse the cell that was created before, but instead recreated it and opened up new storage space.

Is there any good way to solve it?

The principle of cell reuse

(1) iOS device memory is limited, if you use UITableView display thousands of data, you need thousands of UITableViewCell objects, it will deplete the memory of iOS devices. To resolve this issue, you need to reuse the UITableViewCell object

(2) Principle of ⽤: When scrolling the list, some UITableViewCell will be moved out of the window, UITableView will put uitableviewcell outside the window into an object pool, waiting for reuse. When UITableView requires DataSource to return to UITableViewCell, DataSource first looks at the object pool, and if there are unused uitableviewcell in the pool, DataSource will use the new data to configure the UITableViewCell, and then return to UITableView to display the window again to avoid creating new objects. This allows the number of created cell to maintain at a very low level, if a window can only display 5 cell, then the cell reuse, only to create 6 cell is enough.

(3) Note: There are ⼀ very important issues: sometimes the need to customize UITableViewCell (with ⼀ subclass inheritance UITableViewCell), and each ⼀ row ⽤ is not necessarily the same uitableviewcell, so a A uitableview may have different types of uitableviewcell, and there will be many different types of UITableViewCell in the object pool, so UITableView may get the wrong type when ⽤ is used UITableViewCell UITableViewCell

Solution ⽅ Scenario: UITableViewCell has a nsstring *reuseidentifier attribute that can be passed into a specific string identifier when initializing UITableViewCell ( General use of UITableViewCell class name). When UITableView requires DataSource to return to UITableViewCell, the object pool is identified by a string to find the corresponding type of UITableViewCell object, and if so, reuse, if not, Initializes a UITableViewCell object by passing in the string identifier of the ⼀.

Picture example:

Note: A window can be placed (visible) three cell, the entire program only need to create 4 of this type of cell.

Four, the cell optimization code

code example:

Copy Code code as follows:

#import "NJViewController.h"
#import "NJHero.h"

#define ID @ "ABC"

@interface Njviewcontroller () <uitableviewdatasource, uitableviewdelegate>
/**
* Save all the heroic data
*/
@property (nonatomic, strong) Nsarray *heros;
@property (Weak, nonatomic) Iboutlet UITableView *tableview;

@end




Copy Code code as follows:



@implementation Njviewcontroller

#pragma mark-Lazy load


-(Nsarray *) heros


{


if (_heros = = nil) {


1. Get full path


NSString *fullpath = [[NSBundle mainbundle] pathforresource:@ "heros" oftype:@ "plist"];


2. More full path loading data


Nsarray *dictarray = [Nsarray Arraywithcontentsoffile:fullpath];


3. Dictionary Turn model


Nsmutablearray *models = [Nsmutablearray arrayWithCapacity:dictArray.count];


For (Nsdictionary *dict in Dictarray) {


Njhero *hero = [Njhero herowithdict:dict];


[Models Addobject:hero];


}


4. Value Assignment Data


_heros = [models copy];


}


4. Return Data


return _heros;


}

-(void) viewdidload
{
[Super Viewdidload];
Set the height of the cell
Use attributes to set the height of the cell when the cell in each row is highly consistent
Self.tableView.rowHeight = 160;
}

#pragma mark-uitableviewdatasource


How many groups are returned


-(Nsinteger) Numberofsectionsintableview: (UITableView *) TableView


{


return 1;


}


Returns how many rows are in each group


-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section


{


return self.heros.count;


}


When a cell appears in the field of view, it is called


Returns which row of which group to display what content


-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath


{


Defines the value of a variable to hold a reuse token


static NSString *identifier = @ "Hero";





1. First go to the cache pool to find out if there is a cell that satisfies the condition


UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:identifier];


2. If there are no eligible cells in the cache pool, create a cell yourself


if (cell = = nil) {


3. Create the cell and set a unique tag


cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstylesubtitle reuseidentifier:identifier];


NSLog (@ "Create a new cell");


}


4. Set up data for the cell


Njhero *hero = Self.heros[indexpath.row];


Cell.textLabel.text = Hero.name;


Cell.detailTextLabel.text = Hero.intro;


Cell.imageView.image = [UIImage ImageNamed:hero.icon];





NSLog (@ "%@-%d-%p", Hero.name, Indexpath.row, cell);





3. Return cell


return cell;


}

#pragma mark-Control whether the status bar is displayed
/**
* Return Yes to represent the hidden status bar, no instead
*/
-(BOOL) Prefersstatusbarhidden
{
return YES;
}
@end




The idea of caching optimization:

(1) First go to the cache pool to find out if there are conditions for the cell, if there is to directly bring

(2) If not, create a cell on your own

(3) Create a cell and set a unique tag (a chapter that belongs to "")

(4) Setting up data for the cell

Note the point:

The definition variable is used to hold the value of the reuse tag, and it is not recommended to use macros (#define来处理) because the variable is used only within the scope, and if you use a macro definition, the definition and use of the location is too fragmented to benefit the reading program. Because its value is unchanged, it is not necessary to open it up once every time, so it is defined as a static variable with static.

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.