Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a custom cell's textLabel?

When you use the built-in styles (subtitle, right detail, etc) for UITableViewCells, you can access the text labels very easily with textLabel and detailTextLabel which are properties on the UITableViewCell, no matter which style you choose. I used this to my advantage to implement reusable code that allows me to apply specific styles to all of my static cells. But now I want to convert them all to a custom style cell, but with this style I still will only have two labels. My question is, is it possible to manually set the textLabel and detailTextLabel properties for a custom cell? If so, I would not have to change my code, I would just have to simply set the label properties. Otherwise, I'm going to have to change all of my code to target each individual label for each individual cell which will be really messy.

For an example of what I'm doing, I have a method that accepts in a UITableViewCell and in that method I can enable or disable that cell, which changes the labels text colors to black or light gray as appropriate. If I can't access the textLabel and detailTextLabel properties, I'm going to need to add in if statements to compare the cell parameter to my cell outlets to know which labels I need to change.

like image 961
Jordan H Avatar asked Jul 11 '14 15:07

Jordan H


2 Answers

You sure can! Just implement the getters for the labels to redirect to your custom cell's labels.

- (UILabel *)textLabel {
    return self.myCustomCellTextLabel;
}

- (UILabel *)detailTextLabel {
    return self.myCustomCellDetailTextLabel;
}

For people using Swift:

var textLabel: UILabel? {
    return myCustomCellTextLabel
}

var detailTextLabel: UILabel? {
    return myCustomCellDetailTextLabel
}
like image 132
CrimsonChris Avatar answered Nov 10 '22 15:11

CrimsonChris


In custom cell, you have to add all the views in contentView. That's the designed way, and using of existing textField, and detailTextField is not recommended because it may cause undefined behavior by built-in layout logic. (I haven't used them. They may work well. But I will not take the risk)

If you want to avoid patching all existing code, you can try subclass and overriding the properties to labels which created by you.

@interface CustomCell1 : UITableViewCell
@end
@implementation CustomCell1
{
    UILabel* _your_custom_label1;
}
- (UILabel*)textLabel
{
    return _your_custom_label1;
}
@end
like image 1
eonil Avatar answered Nov 10 '22 16:11

eonil