iOS實現TextField游標居中
阿新 • • 發佈:2019-01-21
定義textField:
#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
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去換,然後根據輸入刪除去判斷當前是否有文字輸入。