I have a table view with a custom protoype cell and the cell has 3 different labels on it. How do I get access to these labels? I need to change their texts. I've searched around everywhere and haven't found something that helps me in this case. I have the below code:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basicCell" forIndexPath:indexPath];
//change cell's 3 labels' text here
return cell;
}
How can I access the above cell's 3 different labels that it has?
You need to make a class that is a subclass of UITableViewCell
, and set the custom cell's class to the class you made. Then you want to link the labels using IBOutlet
s in the cell to the subclass you made.
Finally, in -tableView:cellForRowAtIndexPath:
, you should cast the cell to your new subclass so you get access to those IBOutlet
s. Assuming your outlets are named someLabelOutlet1
, someLabelOutlet2
, and someLabelOutlet3
, do the following after you finished subclassing .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
SomeTableViewCellSubclass *cell = (SomeTableViewCellSubclass *)[tableView dequeueReusableCellWithIdentifier:@"basicCell" forIndexPath:indexPath];
cell.someLabelOutlet1.text = @"sometext"
cell.someLabelOutlet2.text = @"sometext"
cell.someLabelOutlet3.text = @"sometext"
return cell;
}
In cellForRowAtIndexPath
, you can access these labels
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell =[tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
if (!cell) {
[tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];
cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
// set common properties here
cell.lbl1.textColor=[UIColor whiteColor];
cell.lbl1.backgroundColor=[UIColor redColor];
cell.lbl1.font=[UIFont fontWithName:@"Verdana" size:16.0];
}
cell.lbl1.text=@"lbl1Txt";
cell.lbl2.text=@"lbl2Txt";
cell.lbl3.text=@"lbl3Txt";
return cell;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.