Search code examples
iosuitextfieldsubclassing

Subclassing UITextField and setting text font


I have a subclass of UITextField so that I can add an IndexPath item to the textfield that looks like this:

@interface jnTextField : UITextField

@property (nonatomic, retain) NSIndexPath *indexPath;

@end

Then I added the textfield to a UITableViewCell in InterfaceBuilder. However now when I try to set text color and font it doesn't set like if I was using the standard UITextField. What else do I need to override to get this working. I wasn't able to find anything explaining what I am missing. The code I am using to change text font/color/text is my cellForRowAtIndexPath method:

cell.textField.text = @"add url";
cell.textField.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0];
cell.textField.textColor = [UIColor blueColor];

Solution

  • The problem is here... you have to avoid using the same property names used by UIKIT classes.

    cell.textField.text = @"add url";
    cell.textField.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0];
    cell.textField.textColor = [UIColor blueColor];
    

    The textField is a property of UITableViewCell class therefore please change the custom UITextField's (jnTextField) name in your custom UITabelViewCell class something like.

    cell.myCustomTextField.text = @"add url";
    cell.myCustomTextField.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0];
    cell.myCustomTextField.textColor = [UIColor blueColor];
    

    To achieve that you might have to case the cell like this

    MYCustomCell *myCell = (MYCustomCell *)cell
    
    myCell.myCustomTextField.text = @"add url";
    myCell.myCustomTextField.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0];
    myCell.myCustomTextField.textColor = [UIColor blueColor];
    

    Hope it will help you.