設(shè)計(jì)師和UITextField干上了枝誊,UITextField的原有格式設(shè)計(jì)大佬不滿(mǎn)意。所以要各種魔改惜纸。
現(xiàn)記錄一下魔改內(nèi)容叶撒。(覺(jué)得寫(xiě)得有幫助的話(huà)不用贊賞,??就好)??耐版。
先看效果
修改TextField光標(biāo)顏色不需要繼承創(chuàng)建子類(lèi)祠够,其他創(chuàng)建子類(lèi)重寫(xiě)方法
1 修改TextField光標(biāo)顏色位置大小
重寫(xiě) - (CGRect)caretRectForPosition:(UITextPosition *)position;方法
#define Flog_H 6 //比原來(lái)光標(biāo)長(zhǎng)度短多少
#define Flog_W 3
#define Flog_M 2 //距離文字的間距原來(lái)
- (CGRect)caretRectForPosition:(UITextPosition *)position{
CGRect originalRect = [super caretRectForPosition:position];
originalRect.size.height = originalRect.size.height - Flog_H;//新光標(biāo)高度
originalRect.size.width = Flog_W; //新光標(biāo)寬度
//計(jì)算光標(biāo)位置
originalRect.origin.x = originalRect.origin.x + Flog_M;
originalRect.origin.y = originalRect.origin.y + ceil(Flog_H/2);
return originalRect;
}
2 修改TextField光標(biāo)顏色
代碼修改:
修改textField.tintColor = newcolor;即可粪牲;
xib如下圖:
3 修改Placeholder顏色字體
重寫(xiě) - (void)drawPlaceholderInRect:(CGRect)rect 古瓤;方法
- (void)drawPlaceholderInRect:(CGRect)rect {
// NSMutableParagraphStyle
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = self.textAlignment; // 居中 不設(shè)置默認(rèn)居左
NSDictionary *attributes = @{
NSForegroundColorAttributeName : _placeholderColor?_placeholderColor:PlaceholderColor,//不設(shè)置默認(rèn)位70%灰
NSFontAttributeName : self.font,//也可以設(shè)置為其他你想要字體,我用的是和輸入一樣的字體
NSParagraphStyleAttributeName : paragraph
};
// 計(jì)算位置
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位置
重寫(xiě) - (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位置
重寫(xiě) - (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使用不一樣對(duì)齊方式
[_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使用方便請(qǐng)看使用“IBInspectable”XIB設(shè)置圓角落君、邊框、陰影