[iOS] 客製化TableViewCell (Custom TableViewCell)

客製化TableViewCell, 照著這3篇做,就成功了,還滿簡單的。

[iOS] 客製化TableViewCell (Custom TableViewCell)
https://cg2010studio.com/2013/05/09/ios-%E5%AE%A2%E8%A3%BD%E5%8C%96tableviewcell-custom-tableviewcell/

Customize Table View Cells for UITableView
http://www.appcoda.com/customize-table-view-cells-for-uitableview/

Customize Table View Cells for UITableView in iOS
http://www.theappguruz.com/blog/customize-table-view-cells-uitableview-ios


實作出來的結果:

 

 


如果是使用標準的內建cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *simpleTableIdentifier = @"SimpleTableItem";
 
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
 
 if (cell == nil) {
 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
 }
 
 cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
 cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
 
 return cell;
}

 


程式碼:

#pragma mark - TableView events

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
 // Return the number of sections.
 return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 return [userArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 static NSString *CellIdentifier = @"IMUserCell";
 //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 IMUserCell *cell = (IMUserCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 
 if (cell == nil){
 NSArray *cells = [[NSBundle mainBundle] loadNibNamed:@"IMUserCell" owner:self options:nil];
 cell = [cells objectAtIndex:0];
 }
 
 //Configure the cell.
 //cell.textLabel.text = [self.colorNames objectAtIndex:[indexPath row]];
 UserInfo *user = [userArray objectAtIndex:[indexPath row]];
 [cell.textLineID setText:user.line_id];
 [cell.textCountry setText:user.country_code];
 [cell.textMessage setText:user.message];
 
 if(user.tag1 && user.tag1.length > 0) {
 NSString *gameTitle = NSLocalizedString(user.tag1, nil);
 cell.btnTag1.layer.cornerRadius = 5;
 [cell.btnTag1 setTitle:gameTitle forState:UIControlStateNormal];
 }
 else
 {
 [cell.btnTag1 setHidden:YES];
 }
 
 if(user.tag2 && user.tag2.length > 0) {
 NSString *gameTitle = NSLocalizedString(user.tag2, nil);
 cell.btnTag2.layer.cornerRadius = 5;
 [cell.btnTag2 setTitle:gameTitle forState:UIControlStateNormal];
 }
 else
 {
 [cell.btnTag2 setHidden:YES];
 }
 
 cell.userPhoto.image = [UIImage imageNamed:@"icon_user_photo_default.png"];

 return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 return 60;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *