LoginSignup
2
1

More than 5 years have passed since last update.

UITextFieldで文字位置を調整する

Last updated at Posted at 2014-12-19

UITextFieldの大きさはそのままで、文字の位置だけを調整する方法

UITextFieldを継承したクラスを作成する。

CustomTextField.h
@interface CustomTextField : UITextField

// プレースホルダー・テキストカラー
@property (nonatomic) UIColor *placeHolderTextColor;

@end 
CustomTextField.m
@implementation CustomTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self) {
        self.font = [UIFont systemFontOfSize:13];
        self.placeHolderTextColor =[UIColor blackColor];
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.returnKeyType = UIReturnKeySearch;
        self.keyboardAppearance = UIKeyboardAppearanceLight;
    }

    return self;
}

- (void)drawPlaceholderInRect:(CGRect)rect
{
    rect.origin.y = (rect.size.height - 10) / 2;
    NSDictionary *attr = @{ NSFontAttributeName: [UIFont systemFontOfSize:13],
                            NSForegroundColorAttributeName: self.placeHolderTextColor };

    [self.placeholder drawWithFrame:rect attributes:attr];
}

- (CGRect)textRectForBounds:(CGRect)bounds
{
    return CGRectOffset(bounds, 5, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return CGRectOffset(bounds, 5, 0);
}

// placeholderの位置調整
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return CGRectOffset(bounds, 5, -2);
}

@end
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1