光標
1. 設置光標顏色
self.textfield.tintColor = [UIColor redColor];
2. 設置光標位置
第一種方法是:設置 leftView ,使得 leftView 填充左間距的位置
CGFloat marginToLeft = 10.f;
UIView *leftView = [[UIView alloc] init];
leftView.frame = CGRectMake(0, 0, marginToLeft, 0);
self.textfield.leftView = leftView;
self.textfield.leftViewMode = UITextFieldViewModeAlways;
第二種方法是:重寫 UITextfield 裏面的方法
#import "UITextField+CursorPosition.h"
CGFloat marginToLeft = 10.f;
@implementation UITextField (CursorPosition)
// 控制編輯文本的位置
- (CGRect)editingRectForBounds:(CGRect)bounds
{
return CGRectMake(bounds.origin.x + marginToLeft, bounds.origin.y, bounds.size.width - marginToLeft, bounds.size.height);
}
// 控制顯示文本的位置
- (CGRect)textRectForBounds:(CGRect)bounds
{
return CGRectMake(bounds.origin.x + marginToLeft, bounds.origin.y, bounds.size.width - marginToLeft, bounds.size.height);
}
@end
佔位符
[self.textfield setValue:[UIColor cyanColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textfield setValue:[UIFont systemFontOfSize:17] forKeyPath:@"_placeholderLabel.font"];
代理
關於 UITextFieldDelegate 的代理方法
// 開始編輯之前,判斷是否允許開始編輯
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
// 開始編輯,成爲第一響應者
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
}
// 結束編輯之前,判斷是否允許結束編輯
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
// 結束編輯,失去第一響應者
- (void)textFieldDidEndEditing:(UITextField *)textField
{
}
// 替換某些範圍的文字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 此處可以用來限制 textField 的內容長度
return YES;
}
// 清空按鈕被點擊之前,判斷是否允許清空
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
return YES;
}
// 'return'鍵被點擊之前,判斷是否允許執行
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
return YES;
}
通知
UIKIT_EXTERN NSString *const UITextFieldTextDidBeginEditingNotification;
UIKIT_EXTERN NSString *const UITextFieldTextDidEndEditingNotification;
UIKIT_EXTERN NSString *const UITextFieldTextDidChangeNotification;
參考資料