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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值