zoukankan      html  css  js  c++  java
  • 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去换,然后根据输入删除去判断当前是否有文字输入。

  • 相关阅读:
    Linux基操:软件安装的方式:解压缩安装
    Linux基操:linux命令失效解决方法
    Linux基操:软件安装的方式:rpm,&&环境变量配置
    Linux基操:进程管理
    Linux基操:磁盘管理,扩展文件挂载问题
    Linux基操(Centos7):用户管理
    Linux基操:文件内容查看方式&&软链接硬链接(拓展)
    Linux基操:目录相关命令
    多测师肖sir_高级金牌讲师__面试和答案归纳
    多测师肖sir__高级金牌讲师 ___python中len函数
  • 原文地址:https://www.cnblogs.com/pengsi/p/7656898.html
Copyright © 2011-2022 走看看