設計師和UITextField干上了,UITextField的原有格式設計大佬不滿意。所以要各種魔改。
現記錄一下魔改內容。(覺得寫得有幫助的話不用贊賞,??就好)??。
先看效果
Untitled.gif
修改TextField光標顏色不需要繼承創建子類,其他創建子類重寫方法
1 修改TextField光標顏色位置大小
重寫 - (CGRect)caretRectForPosition:(UITextPosition *)position;方法
#define Flog_H 6 //比原來光標長度短多少
#define Flog_W 3
#define Flog_M 2 //距離文字的間距原來
- (CGRect)caretRectForPosition:(UITextPosition *)position{
CGRect originalRect = [super caretRectForPosition:position];
originalRect.size.height = originalRect.size.height - Flog_H;//新光標高度
originalRect.size.width = Flog_W; //新光標寬度
//計算光標位置
originalRect.origin.x = originalRect.origin.x + Flog_M;
originalRect.origin.y = originalRect.origin.y + ceil(Flog_H/2);
return originalRect;
}
2 修改TextField光標顏色
代碼修改:
修改textField.tintColor = newcolor;即可;
xib如下圖:
修改TextField光標顏色
3 修改Placeholder顏色字體
重寫 - (void)drawPlaceholderInRect:(CGRect)rect ;方法
- (void)drawPlaceholderInRect:(CGRect)rect {
// NSMutableParagraphStyle
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = self.textAlignment; // 居中 不設置默認居左
NSDictionary *attributes = @{
NSForegroundColorAttributeName : _placeholderColor?_placeholderColor:PlaceholderColor,//不設置默認位70%灰
NSFontAttributeName : self.font,//也可以設置為其他你想要字體,我用的是和輸入一樣的字體
NSParagraphStyleAttributeName : paragraph
};
// 計算位置
CGSize textSize = [self.placeholder sizeWithAttributes:attributes];
CGFloat hdif = rect.size.height - textSize.height;
hdif = MAX(0, hdif);
rect.origin.y += ceil(hdif/2.0);
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
4 修改Placeholder位置
重寫 - (CGRect)placeholderRectForBounds:(CGRect)bounds;方法
- (CGRect)placeholderRectForBounds:(CGRect)bounds{
CGRect originalRect = [super placeholderRectForBounds:bounds];
originalRect.origin.x = originalRect.origin.x +20;
return originalRect ;
}
- (CGRect)textRectForBounds:(CGRect)bounds
5 修改text位置
重寫 - (CGRect)textRectForBounds:(CGRect)bounds方法
- (CGRect)textRectForBounds:(CGRect)bounds{
CGRect originalRect = [super placeholderRectForBounds:bounds];
originalRect.origin.x = originalRect.origin.x +20;
return originalRect ;
}
6 Placeholder和text使用不一樣對齊方式
[_accountTF addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
//判斷是否是空字符串 空字符串
#define NOEmptyStr(string) (string == nil || string == NULL ||[string isKindOfClass:[NSNull class]] || [string isEqualToString: @""] ||[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0 ? NO : YES)
#define IsEmptyStr(string) (!NOEmptyStr(string))
-(void)textChanged:(UITextField *)textField{
if (IsEmptyStr(textField.text)) {
textField.textAlignment = NSTextAlignmentCenter;
}else{
textField.textAlignment = NSTextAlignmentLeft;
}
}
另外為了xib和storyboard使用方便請看使用“IBInspectable”XIB設置圓角、邊框、陰影