ioscocoa-touchuitextfieldalignmentleftalign

Add lefthand margin to UITextField


I want to put the left margin of a UITextField's text at 10 px. What is the best way to do that?


Solution

  • As I have explained in a previous comment, the best solution in this case is to extend the UITextField class instead of using a category, so you can use it explicitly on the desired text fields.

    #import <UIKit/UIKit.h>
    
    @interface MYTextField : UITextField
    
    @end
    
    
    @implementation MYTextField
    
    - (CGRect)textRectForBounds:(CGRect)bounds {
        int margin = 10;
        CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height);
        return inset;
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        int margin = 10;
        CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height);
        return inset;
    }
    
    @end
    

    A category is intended to add new functions to an existing class, not to override an existing method.