在cell中ide
- (void)setModel:(SelectModel *)model { _model = model; if (model.isClick) { self.chooseImage.image = [UIImage imageNamed:@"friend_select"]; }else { self.chooseImage.image = [UIImage imageNamed:@"friend_select_no"]; } self.avartarImage.image = [UIImage imageNamed:model.address]; self.usernameLabel.text = [NSString stringWithFormat:@"%@", model.username]; }
在控制器中code
- (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @"選擇好友"; _dataArray = [NSMutableArray arrayWithCapacity:1]; _selectArray = [NSMutableArray arrayWithCapacity:1]; [self initWithTableView]; [self getData]; // Do any additional setup after loading the view from its nib. } - (void)initWithTableView { self.myTableView.dataSource = self; self.myTableView.delegate = self; [self.myTableView registerNib:[UINib nibWithNibName:[SelectedTableViewCell identifier] bundle:nil] forCellReuseIdentifier:[SelectedTableViewCell identifier]]; self.myTableView.tableFooterView = [UIView new]; self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone; } - (void)getData { NSArray *address = @[@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8"]; NSArray *username = @[@"李秀琴", @"曾津", @"馬倫英", @"廖詩涵", @"張運", @"鄭珠", @"周秀嬌", @"張汝詩"]; NSMutableArray *arr = [NSMutableArray arrayWithCapacity:1]; for (int i=0; i<address.count; i++) { _model = [[SelectModel alloc] init]; _model.isClick = NO; _model.address = address[i]; _model.username = username[i]; [arr addObject:_model]; } [_dataArray addObjectsFromArray:arr]; [self.myTableView reloadData]; } - (IBAction)didConfirmClicked:(id)sender { } #pragma mark UITableViewDelegate, UITableViewDataSource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _dataArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { SelectedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[SelectedTableViewCell identifier]]; cell.model = _dataArray[indexPath.row]; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 44; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; SelectModel *model = _dataArray[indexPath.row]; if (model.isClick) { model.isClick = NO; [_selectArray removeObject:model]; [_dataArray replaceObjectAtIndex:indexPath.row withObject:model]; }else { model.isClick = YES; [_selectArray addObject:model]; [_dataArray replaceObjectAtIndex:indexPath.row withObject:model]; } [self.myTableView reloadData]; }