PS:学习IOS开发的第3天,算是入门了吧,语法格式还不是很习惯,不过心中感觉渐渐明朗。
1.使用Tag来指定控件
PlayersViewController.m ,在PlayersViewcontroller中将cellForRowatIndexPath修改为:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PlayerCell"]; Player *player = [self.players objectAtIndex:indexPath.row]; UILabel *nameLabel = (UILabel *)[cell viewWithTag:100]; nameLabel.text = player.name; UILabel *gameLabel = (UILabel *)[cell viewWithTag:101]; gameLabel.text = player.name; UIImageView * ratingImageView = (UIImageView *) [cell viewWithTag:102]; ratingImageView.image = [self imageForRating:player.rating]; return cell; }
加了这个方法:
- (UIImage *)imageForRating:(int)rating { switch (rating) { case 1: return [UIImage imageNamed:@"1StarSmall.png"]; case 2: return [UIImage imageNamed:@"2StarsSmall.png"]; case 3: return [UIImage imageNamed:@"3StarsSmall.png"]; case 4: return [UIImage imageNamed:@"4StarsSmall.png"]; case 5: return [UIImage imageNamed:@"5StarsSmall.png"]; } return nil; }
2.创立单独的UITableViewCell类:
PlayerCell.h
@interface PlayerCell : UITableViewCell @property (nonatomic, strong) IBOutlet UILabel *nameLabel; @property (nonatomic, strong) IBOutlet UILabel *gameLabel; @property (nonatomic, strong) IBOutlet UIImageView *ratingImageView; @endPlayerCell.m
#import "PlayerCell.h" @implementation PlayerCell @synthesize nameLabel; @synthesize gameLabel; @synthesize ratingImageView; @end回到MainStoryboard.storyboard选中原型单元格,将他的class属性修改为“PlayerCell”,现在当你向table view请求dequeueReusableCellWithIdentifier,他会返回一个PlayerCell实例而不是一个普通的UITableViewCell实例。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { PlayerCell *cell = (PlayerCell *)[tableView dequeueReusableCellWithIdentifier:@"PlayerCell"]; Player *player = [self.players objectAtIndex:indexPath.row]; cell.nameLabel.text = player.name; cell.gameLabel.text = player.game; cell.ratingImageView.image = [self imageForRating:player.rating]; return cell; }