hello 大家又見面啦,今天小編給大家講解一下UITableView,這一塊知識在我們實際項目中是最為常見的,是ios項目的根骨所在,希望大家能夠足夠重視,所以小編準備分幾次內容給大家一一解析其中的難點,下面是最基礎的內容,希望大家能有所收獲。
~~~
import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDataSource>
//綁定tableView控件,定義變量,方便對控件的代碼操作
@property (strong, nonatomic) IBOutlet UITableView *table;
//為tableView上顯示數據定義兩個變量
@property(nonatomic,strong)NSArray *community;
@property(nonatomic,strong)NSArray *details;
@end
~~~
~~~
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize details;
@synthesize community;
- (void)viewDidLoad {
[super viewDidLoad];
//對定義的兩個變量賦予初始值
community=[NSArray arrayWithObjects:@"圖靈工作社",@"夢翔工作社",@"南工電腦網",@"鋒芒工作社", nil];
details=[NSArray arrayWithObjects:@"圖靈最牛,擠壓群熊",@"不錯的社團",@"不錯的社團",@"不錯的社團", nil];
self.table.dataSource=self;
//添加頁眉和頁腳,在這里小編分別加載的是圖片
self.table.tableHeaderView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"001.jpg"]];
self.table.tableFooterView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"001.jpg"]];
}
//UITableView協議里面的方法,對每個UITableCell進行定制和寫入內容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId=@"cellId";//靜態NSString類型,目的是可以重用能添加UITaleCell到重用表格中,和方便從重用表格中調取。
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
if (cell==nil) {//第一次沒有表格行(UITableCell)時,定制表格行
switch (indexPath.row%4) {
case 0:
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];//第一種UITableCell風格
break;
case 1:
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];//第二種UITableCell風格
break;
case 2:
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];//第三種UITableCell風格
break;
case 3:
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellId];//第四種UITableCell風格
break;
<span style="color:#ff0000;">//注意看下下邊的圖片,比較這四種UITableCell的不同點!!!</span>
}
}
NSUInteger rowNo=indexPath.row;//調取每行UITableCell的索引進行付于初值
cell.textLabel.text=[community objectAtIndex:rowNo];
cell.imageView.image=[UIImage imageNamed:@"001.jpg"];
cell.imageView.highlightedImage=[UIImage imageNamed:@"001.jpg"];
cell.detailTextLabel.text=[details objectAtIndex:rowNo];
return cell;
}
//UIDataSource協議里面的第二個方法:目的告訴系統一個分區里面有多少個表格行(注意是一個分區,不一定是總共有多少表格行)
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return community.count;
}
//UIDataSource協議里面的第二個方法:目的告訴系統有幾個分區(幾塊表格)顯然這里返回的是一個分區表格
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
~~~
運行結果如下:

怎么樣,這點簡單的知識掌握了沒有啊?大家要愉快的學習,發覺編程的樂趣,提高自己的效率!后續馬上給大家講解深層次的UITableView知識,希望小編的這點微薄知識能幫到你們!


