NSTextAlignmentCenter不适用于自定义文本字段

时间:2016-06-29 04:26:31

标签: ios objective-c uitextfield

我正在为UITextField创建自定义文本字段。

我使用self.textAlignment = NSTextAlignmentCenter;来设置文本对齐方式,但是当我开始编辑时,光标的初始位置是左侧而不是中心位置。然而,当我输入某些内容时,文本处于中心位置。

textRectForBounds:editingRectForBounds:都返回相同的CGRect值。

以下是代码:

@interface MyTextfield () <UITextFieldDelegate>

@end

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

    if (self) {
        self.delegate = self;
        self.textAlignment = NSTextAlignmentCenter;
    }

    return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
    return  CGRectInset(bounds, 20.5, 4.5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return  CGRectInset(bounds, 20.5, 4.5);
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // Do some animation
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    // Do some animation
}

问题是什么?我该如何解决?

1 个答案:

答案 0 :(得分:0)

首先创建一个UITextField类。

CustomTextfield.h

#import <UIKit/UIKit.h>

@interface CustomTextfield : UITextField
@end

CustomTextfield.m

#import "CustomTextfield.h"
@interface CustomTextfield () <UITextFieldDelegate>

@end

@implementation CustomTextfield
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.textAlignment = NSTextAlignmentCenter;
        self.font = [UIFont systemFontOfSize:15];
        self.placeholder = @"Test";
        self.autocorrectionType = UITextAutocorrectionTypeNo;
        self.keyboardType = UIKeyboardTypeDefault;
        self.returnKeyType = UIReturnKeyDone;
        self.textAlignment = NSTextAlignmentCenter;
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        self.borderStyle=UITextBorderStyleRoundedRect;
    }

    return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
    return  CGRectInset(bounds, 20.5, 4.5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return  CGRectInset(bounds, 20.5, 4.5);
}

现在将CustomTextfield类用于您的视图控制器。

-(void)viewDidLoad{
    UITextField *txtEmailfield = [[CustomTextfield alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
    txtEmailfield.delegate = self;

    [self.view addSubview:txtEmailfield];
}

注意:在此视图控制器中,请将此添加到@interface yourviewcontroller name() <UITextFieldDelegate>