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去換,然后根據輸入刪除去判斷當前是否有文字輸入。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM