本文轉載於容芳志的blog http://blog.csdn.net/totogo2010/article/details/7642908,在此表示感謝。
Table View簡單描述:
在iPhone和其他iOS的很多程序中都會看到Table View的出現,除了一般的表格資料展示之外,設置的屬性資料往往也用到Table View,Table View主要分爲以下兩種:
- Plain:這是普通的列表風格
- Grouped :這是分塊風格。
1、新建項目
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
- @property (strong, nonatomic) NSArray *list;
- @end
5、打開.m文件,添加:
- @synthesize list = _list;
這是發現有兩個警告,提示未完成的實現,這提示的是UITableViewDelegate, UITableViewDataSource這個兩個頭文件裏的協議的方法未實現。待會我們去實現它。
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- NSArray *array = [[NSArray alloc] initWithObjects:@"美國", @"菲律賓",
- @"黃巖島", @"中國", @"泰國", @"越南", @"老撾",
- @"日本" , nil];
- self.list = array;
- }
- - (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- self.list = nil;
- }
7、生成row
- - (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 = [self.list objectAtIndex:row];
- return cell;
- }
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier];
這個語句根據標識符TableSampleIdentifier尋找當前可以重用的UITableViewCell。當某行滑出當前可見區域後,我們重用它所對應的UITableViewCell對象,那麼就可以節省內存和資源。
注意參數(NSIndexPath *)indexPath,它將行號row和部分號section合併了,通過[indexPath row];獲取行號。之後給cell設置其文本:
cell.textLabel.text = [self.list objectAtIndex: row];
- NSUInteger row = [indexPath row];
- cell.textLabel.text = [self.list objectAtIndex:row];
- UIImage *image = [UIImage imageNamed:@"qq"];
- cell.imageView.image = image;
- UIImage *highLighedImage = [UIImage imageNamed:@"youdao"];
- cell.imageView.highlightedImage = highLighedImage;
- return cell;
效果如下:
UITableViewCellStyleDefault
UITableViewCellStyleSubtle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
cell.detailTextLabel.text =@"打打打打";
return cell;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
選中是做個提示,提示選中了那個信息,代碼實現如下:
- -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
- NSString *rowString = [self.list objectAtIndex:[indexPath row]];
- UIAlertView * alter = [[UIAlertView alloc] initWithTitle:@"選中的行信息" message:rowString delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
- [alter show];
- }
效果: