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去换,然后根据输入删除去判断当前是否有文字输入。

  • 相关阅读:
    ecnu1624求交集多边形面积
    poj2986A Triangle and a Circle&&poj3675Telescope(三角形剖分)
    poj2194Stacking Cylinders
    zoj2589Circles(平面图的欧拉定理)
    poj1819Disks
    poj3334Connected Gheeves(二分)
    2014 Multi-University Training Contest 5
    hdu3264Open-air shopping malls(二分)
    poj1375Intervals(点到圆的切线)
    级数基础
  • 原文地址:https://www.cnblogs.com/pengsi/p/7656898.html
Copyright © 2011-2022 走看看