UITableView is used to display data in tabular form. Regarding UITableView, we should note:
(1) UITableView is used to display the visible part of the table, UITableViewCell to display a row of the table.
(2) UITableView is not responsible for storing the data in the table, but simply storing enough data to make the current visible part.
(3) UITableView obtains the configuration information from the Uitableviewdelegate protocol and obtains the data information from the Uitableviewdatasource protocol.
(4) All UITableView implementations actually have only one column, but we can add a child view to the UITableViewCell so that it looks like several columns.
(5) There are two styles of UITableView:
①grouped: Each group looks like a round rectangle;
②plain: This is the default style and can be modified into indexed style.
UITableViewCell Use instances
in the small example below, we will first implement the display of a column of data, and then add the image in each row, and then look at the UITableViewCell four different types of what. Finally, there are other actions, such as setting indents, modifying font size, and row high.
1, run Xcode 4.2, create a new single View application, named Table Sample:
2, click Viewcontroller.xib, add a UITableView control to the view using Interface Builder, and make it overlay the entire view:
3, select the newly added UITableView control, open connection Inspector, find delegate and DataSource, pull the string from the right circle to the file's owner icon:
4, click ViewController.h, add code in it:
Copy Code code as follows:
#import <UIKit/UIKit.h>
@interface Viewcontroller:uiviewcontroller<uitableviewdelegate, uitableviewdatasource>
@property (Strong, nonatomic) Nsarray *listdata;
@end
5, click VIEWCONTROLLER.M, add code in it:
5.1 Add code after @implementation:
Copy Code code as follows:
5.2 Adding code to the Viewdidload method:
Copy Code code as follows:
-(void) viewdidload
{
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.
Nsarray *array = [[Nsarray alloc] initwithobjects:@ "tree", @ "Flower",
@ "Grass", @ "Fence", @ "house", @ "Table", @ "Chair",
@ "book", @ "Swing", nil];
Self.listdata = array;
}
5.3 Adding code to the Viewdidunload method:
Copy Code code as follows:
-(void) viewdidunload
{
[Super Viewdidunload];
Release any retained subviews of the main view.
e.g. Self.myoutlet = nil;
Self.listdata = nil;
}
5.4 Add code before @end:
Copy Code code as follows:
#pragma mark-
#pragma mark Table View Data Source Methods
return number of rows
-(Nsinteger) TableView: (UITableView *) TableView
Numberofrowsinsection: (nsinteger) Section {
return [Self.listdata Count];
}
Creates a new row and returns
-(UITableViewCell *) TableView: (UITableView *) TableView
Cellforrowatindexpath: (Nsindexpath *) Indexpath {
static NSString *tablesampleidentifier = @ "Tablesampleidentifier";
UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:
Tablesampleidentifier];
if (cell = = nil) {
cell = [[UITableViewCell alloc]
Initwithstyle:uitableviewcellstyledefault
Reuseidentifier:tablesampleidentifier];
}
Nsuinteger row = [Indexpath row];
Cell.textLabel.text = [Listdata objectatindex:row];
return cell;
}
In the second method above,
Copy Code code as follows:
UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:tablesampleidentifier];
This statement searches for UITableViewCell that are currently reusable based on the identifier tablesampleidentifier. When a row slips out of the current visible area, we reuse the UITableViewCell object it corresponds to, saving memory and time.
If the cell is nil after the word is executed, then we create another one and set the identifier to be tablesampleidentifier:
Copy Code code as follows:
cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:tablesampleidentifier];
Here Uitableviewcellstyledefault is a constant that represents the UITableViewCell style, and there are other styles that will be used later.
Note the parameter (Nsindexpath *) Indexpath, which merges line number row and part number section, and gets the line number through [Indexpath row]; Then set its text to the cell:
Copy Code code as follows:
Cell.textLabel.text = [Listdata objectatindex:row];
6. Run it:
7. Add pictures to each line:
7.1 Add the picture resource to the project: drag it to the project, as mentioned in the previous article.
7.2 Add the code before the return statement of the Cellforrowatindexpath method:
Copy Code code as follows:
UIImage *image = [uiimage imagenamed:@ "Blue.png"];
Cell.imageView.image = image;
UIImage *highlighedimage = [uiimage imagenamed:@ "Yellow.png"];
Cell.imageView.highlighedImage = Highlighedimage;
7.3 operation, the effect is as follows:
As you can see, a picture appears on the left side of each line. A row in the election whose picture changes.
8, set the style of the line:
Constants that represent the UITableViewCell style are:
Copy Code code as follows:
Uitableviewcellstyledefault
Uitableviewcellstylesubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
The differences in these styles are mainly embodied in image, text label, and detail text label.
To reflect the style, add the code before the return statement of the Cellforrowatindexpath method:
Copy Code code as follows:
Cell.detailTextLabel.text = @ "Detail text";
Then the
Copy Code code as follows:
cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:tablesampleidentifier];
The Uitableviewcellstyledefault in turn is replaced by the four style constants mentioned above and run with the following effects:
Uitableviewcellstyledefault
Uitableviewcellstylesubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
9. Set Indent:
Change the style of all rows back to Uitableviewcellstyledefault, and then add the following code before @end:
Copy Code code as follows:
#pragma mark Table Delegate Methods
-(Nsinteger) TableView: (UITableView *) TableView Indentationlevelforrowatindexpath: (Nsindexpath *) IndexPath {
Nsuinteger row = [Indexpath row];
return row;
}
The row line is indented here, as shown in the following illustration:
10, Operation line selection:
Add code before @end:
Copy Code code as follows:
-(Nsindexpath *) TableView: (UITableView *) TableView Willselectrowatindexpath: (Nsindexpath *) IndexPath {
Nsuinteger row = [Indexpath row];
if (row%2 = = 0) {
return nil;
}
return indexpath;
}
The above method executes before a row is selected, and we can add the action we want to in this method. Here, we realize that if the selected line number (starting from 0) is even, the selection is deselected.
Add code before @end:
Copy Code code as follows:
-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath {
Nsuinteger row = [Indexpath row];
NSString *rowvalue = [Listdata objectatindex:row];
NSString *message = [[NSString alloc] Initwithformat:
@ "You selected%@", Rowvalue];
Uialertview *alert = [[Uialertview alloc]
initwithtitle:@ "Row selected!"
Message:message
Delegate:nil
cancelbuttontitle:@ "Yes I Did"
Otherbuttontitles:nil];
[Alert show];
[TableView Deselectrowatindexpath:indexpath Animated:yes];
}
When a row is selected, an alert is displayed to show the choices we make.
Run, you will find No. 0, 2 and other lines can not choose. Select odd rows to pop-up prompts:
And when the prompt box is closed, the selected line is also canceled, with the statement
Copy Code code as follows:
[TableView Deselectrowatindexpath:indexpath Animated:yes];
11, set the font size and table row height:
11.1 Add code before return in the Cellforrowatindexpath method to set the font and size:
Copy Code code as follows:
Cell.textLabel.font = [Uifont boldsystemfontofsize:50];
11.2 Add code before @end to set the row height:
Copy Code code as follows:
-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath {
return 70;
}
Run, look at the effect:
UITableViewCell that can be customized arbitrarily
The UITableView is more powerful than any custom UITableViewCell cell. Normally, the cell in the UITableView is dynamic, and during use, a cell pool is created, depending on the height of each cell (i.e. Tableview:heightforrowatindexpath: return value), And a few cell displays in the screen height calculation screen. The custom Tableviewcell is to implement the code or use the IB edit nib file to achieve two ways, this article mainly collects code to achieve a variety of cell customization.
1. How to adjust cell height dynamically
Copy Code code as follows:
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath {
static NSString *cellidentifier = @ "Cell";
UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier];
if (cell = = nil) {
cell = [[[[UITableViewCell alloc] Initwithframe:cgrectzero reuseidentifier:cellidentifier] autorelease];
Uilabel *label = [[Uilabel alloc] Initwithframe:cgrectzero];
Label.tag = 1;
Label.linebreakmode = Uilinebreakmodewordwrap;
Label.highlightedtextcolor = [Uicolor Whitecolor];
Label.numberoflines = 0;
Label.opaque = NO; Select opaque to indicate that nothing behind the view should be drawn
Label.backgroundcolor = [Uicolor Clearcolor];
[Cell.contentview Addsubview:label];
[Label release];
}
Uilabel *label = (Uilabel *) [cell viewwithtag:1];
NSString *text;
Text = [Textarray ObjectAtIndex:indexPath.row];
CGRect cellframe = [cell frame];
Cellframe.origin = cgpointmake (0, 0);
Label.text = text;
CGRect rect = Cgrectinset (Cellframe, 2, 2);
Label.frame = rect;
[Label SizeToFit];
if (Label.frame.size.height > 46) {
CellFrame.size.height = m + label.frame.size.height-46;
}
else {
CellFrame.size.height = 50;
}
[Cell Setframe:cellframe];
return cell;
}
-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath
{
UITableViewCell *cell = [self Tableview:tableview cellforrowatindexpath:indexpath];
return cell.frame.size.height;
}
2. How to use the Picture custom table Separeator Split Line
In general, you can modify the color of a cell's middle split line by using a similar [TableView Setseparatorcolor:[uicolor Redcolor]] statement. So how do you use a picture as a dividing line background? You can try the following:
Method One:
First set the cell Separatorcolor to clear, and then add the split line from the picture to the custom cell.
Method Two:
After adding a pixel ImageView to the cell, load the picture into, then set tableview.separatorstyle = Uitableviewcellseparatorstylenone
3. Customize the first row of the cell and its navigation bar spacing
Copy Code code as follows:
Tableview.tableheaderview = [[[UIView alloc] Initwithframe:cgrectmake (0,0,5,20)] autorelease];
4. Custom UITableViewCell Accessory Style
The default Accessorytype property has four values: Uitableviewcellaccessorynone, Uitableviewcellaccessorydisclosureindicator, Uitableviewcellaccessorydetaildisclosurebutton, Uitableviewcellaccessorycheckmark. If you want to use the other styles of a custom attachment button, you need to specify it by using the UITableView Accessoryview property.
Copy Code code as follows:
UIButton *button;
if (Iseditableornot) {
UIImage *image = [uiimage imagenamed:@ "Delete.png"];
button = [UIButton buttonwithtype:uibuttontypecustom];
CGRect frame = CGRectMake (0.0,0.0,image.size.width,image.size.height);
Button.frame = frame;
[Button Setbackgroundimage:image Forstate:uicontrolstatenormal];
Button.backgroundcolor = [Uicolor Clearcolor];
Cell.accessoryview = button;
}else{
button = [UIButton buttonwithtype:uibuttontypecustom];
Button.backgroundcolor = [Uicolor Clearcolor];
Cell.accessoryview = button;
}
The above code only defines the attachment button in two states of the style, the problem is that the custom attachment button is now the event is still unavailable. That is, the event is not yet delivered to the Uitableviewdelegate Accessorybuttontappedforrowwithindexpath method. When we add the following statement in the above code:
Copy Code code as follows:
[Button addtarget:self action: @selector (btnclicked:event:) forcontrolevents:uicontroleventtouchupinside];
After that, although we can capture the click event for each attachment button, we are not able to distinguish exactly which line of attachment button has clicked! Because the Addtarget: method allows up to two arguments: Target and event, both of which have their own purpose (target points to the event delegate object, which points to the event that occurred). It seems that only relying on the cocoa framework can not be done.
But we can still use the event parameter to determine in the custom Btnclicked method which cell the event occurs on UITableView. Because UITableView has a very critical way to indexpathforrowatpoint, depending on where the touch takes place, return to the indexpath of which cell the touch occurs. And by the event object, you can also get the position of each touch in the view.
Copy Code code as follows:
Check the position of the user when clicking on the button and forward the event to the corresponding accessory tapped event
-(void) btnclicked: (ID) Sender event: (ID) event
{
Nsset *touches = [Event Alltouches];
Uitouch *touch = [touches anyobject];
Cgpoint currenttouchposition = [Touch LocationInView:self.tableView];
Nsindexpath *indexpath = [Self.tableview indexpathforrowatpoint:currenttouchposition];
if (Indexpath!= nil)
{
[Self TableView:self.tableView accessorybuttontappedforrowwithindexpath:indexpath];
}
}
In this way, the UITableView Accessorybuttontappedforrowwithindexpath method is triggered and a indexpath parameter is obtained. With this indexpath parameter, we can tell exactly which line of the attachment button has touched the event.
Copy Code code as follows:
-(void) TableView: (UITableView *) TableView Accessorybuttontappedforrowwithindexpath: (Nsindexpath *) IndexPath
{
int *idx = Indexpath.row;
Here to add your own logic
}