標籤:
1 #import "ViewController.h" 2 3 @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> 4 5 @property (strong, nonatomic) UITableView *tableview; 6 7 @property (strong, nonatomic) NSArray *dataSource; 8 9 @end10 11 /*12 UITableView13 表格視圖:兩個協議,兩個代理,四個方法14 15 兩個協議:16 1.資料來源協議:(提供表格式資料,提供表格內容)UITableViewDataSource17 2.執行代理協議:(提供表格操作方法)UITableViewDelegate18 */19 20 21 @implementation ViewController22 23 #pragma mark - LifeCircle24 - (void)viewDidLoad {25 [super viewDidLoad];26 27 [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];28 29 self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 375, 400) style:UITableViewStyleGrouped];30 31 self.tableview.delegate = self;32 self.tableview.dataSource = self;33 34 [self.view addSubview:self.tableview];35 36 NSArray *arr1 = @[@"芃,你好1",@"芃,你好2",@"芃,你好3",@"芃,你好4",@"芃,你好5"];37 NSArray *arr2 = @[@"芃,你好6",@"芃,你好7",@"芃,你好8",@"芃,你好9"];38 self.dataSource = @[arr1,arr2];39 40 41 }42 43 #pragma mark - UITableViewDataSource44 //組數45 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView46 {47 return [self.dataSource count];48 }49 50 //設定每組行數51 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section52 {53 return [[self.dataSource objectAtIndex:section] count];54 }55 56 // 設定[每一個]儲存格方法57 // 1.設定複用[儲存格]ID58 // 2.設定複用59 // 3.建立儲存格60 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath61 {62 // 1.設定複用[儲存格]ID63 static NSString *cellIdentifier = @"cellIdentifier";64 // 2.設定複用65 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];66 // 3.建立儲存格67 if (!cell) {68 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];69 }70 cell.textLabel.text = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];71 72 return cell;73 }74 75 #pragma mark - UITableViewDelegate76 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath77 {78 //拿到點擊的那一行79 UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];80 81 NSString *titleInRow = [NSString stringWithFormat:@"%@",selectCell.textLabel.text];82 83 // NSString *titleInRow = [NSString stringWithFormat:@"%@",[[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];84 85 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"問候" message:titleInRow delegate:self cancelButtonTitle:@"你好" otherButtonTitles: nil];86 [alert show];87 }88 89 @end
iOS UI-表格控制器(UITableView)-基本使用