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