Objective-c UI UITableView Detailed

Source: Internet
Author: User



UITableView occupies a very important position in iOS development and must be mastered.



Before you learn UITableView, learn some basic concepts:


    • UITableView inherits from Uiscrollview, which is a control that can be scrolled vertically
    • Each of the UITableView's data corresponds to a cell called cell, which is an object of UITableViewCell , inherited from UIView
    • UITableView can be partitioned to show that each partition is called a section, each row is called row, and the numbering starts at 0
    • The system provides a class to integrate section and row, called Nsindexpath


As you can see from the above, section and row represent the position of a uitableviewcell on UITableView



Below, we create a uitableview:


// style is a parameter of type UITableViewStyle, is an enumerated type, including UITableViewStylePlain, UITableViewStyleGrouped
UITableView * tableView = [[UITableView alloc] initWithFrame: self.view.bounds style: UITableViewStylePlain];

[self.view addSubview: tableView];


The following are the common properties of UITableView:


RowHeight Row height
Separatorstyle Separator line Style
Separatorcolor Separator Line Color
Tableheaderview Top view of UITableView
Tablefooterview UITableView Bottom View

















UITableView Foundation



There are two important attributes in UITableView: DataSource (following the Uitableviewdatasource Protocol) and delegate (following the Uitableviewdelegate protocol)



Where DataSource is the agent associated with the display data, delegate is the agent associated with the view operation



There are two protocol methods that must be implemented in the Uitableviewdatasource protocol:


-(Nsinteger) TableView: (uitableview *) TableView numberofrowsinsection: (nsinteger) section;

UITableView the number of rows that each partition contains

-(uitableviewcell *) TableView: (uitableview *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath;

Cell to display for each row














The first method can return a different number of rows depending on the given parameter section



The second method: TableView each time a cell is displayed, this method is called to get






Each cell of the UITableView is an object of the UITableViewCell class, which provides three view properties by default:


    1. Picture view: Uiimageview *imageview
    2. Title View: UILabel *textlabel
    3. Subtitle View: UILabel *detailtextlabel


The following is an example of returning a cell: (without using registerclass registration)


-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
     static NSString * cellID = @ "cell";

     // Find the available Cell in the reuse pool of tableView by the identifier (in fact, it is a variable collection inside the reuse pool)
     UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: cellID];

     // If there is no cell corresponding to this identifier in the reuse pool, create a new one and set the identifier
     if (! cell) {
         // Do only Cell style processing in the code block, do not set data
         cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue2 reuseIdentifier: cellID];
     }

     // Set data for Cell
     [cell.textLabel setText: @ "title"];
     [cell.detailTextLabel setText: @ "Description: This is a subtitle"];
    
     return cell;
}


UITableView has a reuse pooling mechanism to manage cells to display all of the data with as few cells as possible



UITableView the process of reusing cells


    1. When a cell is slid out of the screen, the cell is placed in the appropriate reuse pool by the system.
    2. When TableView needs to display a cell, it will first try to get a cell in the reuse pool
    3. If the reuse pool does not have a cell, a cell is created
    4. The cell will be re-assigned after it is acquired.


After creating the UITableView, you need to register a cell class that automatically creates a cell when there is no cell in the reuse pool. Related methods:



[TableView registerclass: (Class) cellclass forcellreuseidentifier: (nsstring *) identifier]; (Multiple registrations can be made using different identifier)



The system provides a way to get the cells in the reuse pool (requires a reuse identity):



-(uitableviewcell *) Dequeuereusablecellwithidentifier: (nsstring *) identifier;






Common protocol methods for UITableView


    • Uitableviewdatasource

-(Nsinteger) Numberofsectionsintableview: (uitableview *) tableView

UITableView Number of partitions

-(nsstring *) TableView: (uitableview *) TableView titleforheaderinsection: (nsinteger) section

Top title of the partition

-(nsstring *) TableView: (uitableview *) TableView titleforfooterinsection: (nsinteger) section

The bottom title of the partition

-(nsarray *) Sectionindextitlesfortableview: (uitableview *) tableView

UITableView the right side of the index record

























    • Uitableviewdelegate

-(void) TableView: (uitableview *) TableView Didselectrowatindexpath: (nsindexpath *) Indexpath

Tell delegate to select a cell.

-(cgfloat) TableView: (uitableview *) TableView Heightforrowatindexpath: (nsindexpath *) Indexpath

The height of each row

-(cgfloat) TableView: (uitableview *) TableView heightforheaderinsection: (nsinteger) Section

The top height of each partition

-(UIView *) TableView: (uitableview *) TableView viewforheaderinsection: (nsinteger) section

Custom views at the top of each partition





























UITableView Edit



Process:

Let TableView in edit state: [TableView setediting: (BOOL) editing animated: (bool) animated];

Determine if the cell is in edit state:

// Rewrite the protocol method of UITableViewDataSource to determine which cells are in edit state according to indexPath, return YES to edit, NO to not edit
-(BOOL) tableView: (UITableView *) tableView canEditRowAtIndexPath: (NSIndexPath *) indexPath;
Set the cell editing style (delete, add):
// Rewrite the protocol method of UITableViewDelegate. According to indexPath, you can determine the editing style of the cell. Do you want to add UITableViewCellEditingStyleInsert or delete UITableViewCellEditingStyleDelete, or do not edit UITableViewCellEditingStyleNone
-(UITableViewCellEditingStyle) tableView: (UITableView *) tableView editingStyleForRowAtIndexPath: (NSIndexPath *) indexPath;
Edit status to submit:
// Override UITableViewDataSource protocol method, delete Cell at indexPath according to editingStyle, or insert Cell at indexPath, modify data source
-(void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath *) indexPath;
 Note: After editing, because the protocol method numberOfRowInSection is only called once when the tableView is added to the parent view, and the data on the table is provided by the array, therefore, you need to change the data in the array first, and then let the table protocol renew Call for reassignment

That is, first modify the data source and refresh the table (using the [table reloadData] method to refresh)

 

UITableView mobile

Implement a protocol that tells whether the tableView can be moved:
// Return YES to allow movement
-(BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath;
mobile:
// Modify the data source, and then [tableView reloadData] update the tableView view data
-(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) sourceIndexPath toIndexPath: (NSIndexPath *) destinationIndexPath
 

UITableViewCell

1. Custom Cell

Create a class that inherits from UITableViewCell
Implement the UITableViewCell initialization method:-(instancetype) initWithStyle: (UITableViewCellStyle) style reuseIdentifier: (NSString *) reuseIdentifier
Ensure that all added subviews are created in the custom Cell initialization method to avoid duplicate creation of subviews
After the subview of the Cell is successfully created, set the subview as a property, which is convenient for assigning values to the custom view in the UITableView protocol.
In general, the frame size of the Cell when it is created is (0,0,320,44), and the height of the Cell we set is generally greater than 44. Therefore: the frame for creating the subview in the custom cell is CGRectZero. The frame is set for the subview when the Cell is added to the tableView. When the Cell is added to the tableView, the size has been changed to the size set by the tableView, so set the frame of the subview in the custom Cell method layoutSubviews

2.Use of Model

The role of the Model class is to provide us with data. Generally, our data is stored in arrays and dictionaries. KVC in OC exists to help us convert dictionaries into Model classes.

Steps for usage:

Create a Model class inherited from NSObject
Add the corresponding attribute in the dictionary, the attribute name must be the same as the dictionary key value, except for the system keyword
Assign a dictionary to a model in KVC using a view controller
Add Model objects to the array and refresh the tableView
Note: The Model class must be overridden-(void) setValue: (id) value forUndefinedKey: (NSString *) key, to prevent the crash if the property with the same key value cannot be found. The method assigns a value to the corresponding attribute (the attribute name and the system keyword do not conflict), such as _id = value;

3.Multiple use of Cell

Different Cells need to be distinguished by different reuse identifiers, and the distinction of reuse identifiers needs to be distinguished according to different situations, such as:

Model attribute distinction (different data content, such as the type field in the data, 0 represents the text type, 1 represents the picture type)
Cell types displayed in fixed rows are different
4.Adaptive height

Text adaptive height:
// Get font style attributes
NSDictionary * att = @ {NSFontAttributeName: [UIFont systemFontOfSize: 18.0]};
// Get the height according to the font style attribute
CGRect rect = [string boundingRectWithSize: CGSizeMake (300, MAXFLOAT) options: NSStringDrawingUsesLineFragmentOrigin attributes: att context: nil];
// Reset the frame to display the text control
[self.label setFrame: CGRectMake (0,0,300, rect.size.height)];

// We can define a class specifically used to calculate the text height, so that it can be called directly when used
Cell adaptive height:
Through the protocol method-(CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath sets the height of the cell

Set the height of the subviews in the layoutSubviews method in the custom Cell
 

 

Reprint please indicate: Author SmithJackyson

Detailed UITableView of Objective-C UI

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.