光标
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;
参考资料
本文详细介绍如何自定义 UITextField 的光标颜色、位置及占位符样式,并深入探讨 UITextField 的代理方法和通知机制,帮助开发者掌握 UITextField 的高级用法。
722

被折叠的 条评论
为什么被折叠?



