iOS实现TextField光标居中

//
//  MyTextField.m
//  DriverEpoch
//
//  Created by 思 彭 on 2017/10/12.
//  Copyright © 2017年 http://halohily.com. All rights reserved.
//

#import "MyTextField.h"

@implementation MyTextField

-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
    CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width -20, bounds.size.height);//更好理解些
    return inset;
}


// 修改文本展示区域,一般跟editingRectForBounds一起重写
- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些
    return inset;
}

// 重写来编辑区域,可以改变光标起始位置,以及光标最右到什么地方,placeHolder的位置也会改变
-(CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect inset;
    if (self.text.length > 0) {
        // 这里100可能需要自己调整一下使其居中即可
        inset = CGRectMake(bounds.origin.x + 100, bounds.origin.y, bounds.size.width - bounds.size.width / 2, bounds.size.height);//更好理解些
    }
//    NSLog(@"%@",self.text);
    else {
        
        inset = CGRectMake(bounds.origin.x+bounds.size.width / 2, bounds.origin.y, bounds.size.width - bounds.size.width / 2, bounds.size.height);//更好理解些
    }
    return inset;
}


@end

定义textField:

 username = [[MyTextField alloc] initWithFrame:CGRectMake(DEAppWidth * 0.04, 0, DEAppWidth * 0.84, 40)];
    username.backgroundColor = [UIColor lightGrayColor];
    username.delegate = self;
    username.textAlignment = NSTextAlignmentCenter;
//    username.backgroundColor = [UIColor lightGrayColor];
    username.textColor = [UIColor blackColor];
    username.font = [UIFont fontWithName:@"Times New Roman" size:12];
    username.placeholder = @"请输入用户名";
    username.autocorrectionType = UITextAutocorrectionTypeNo;
    username.autocapitalizationType = UITextAutocapitalizationTypeNone;
    username.clearButtonMode = UITextFieldViewModeWhileEditing;

实现效果如下:

注意: 这里截图光标不明显,实际光标是在“入”和“用”字中间的。。。

这里还是有些小bug。。。待完善。。。

小技巧:

可以用个假象去代替,就是直接文字居中,然后点击光标时候就把灰色底子用label去换,然后根据输入删除去判断当前是否有文字输入。

原文地址:https://www.cnblogs.com/pengsi/p/7656898.html