|
#import "UITextField+TintClearButton.h" |
|
@import ObjectiveC.runtime; |
|
|
|
UIImage* UITFC_tintImage(UIImage* image, UIColor* color) |
|
{ |
|
CGSize size = image.size; |
|
|
|
UIGraphicsBeginImageContextWithOptions(size, false, 0); |
|
CGContextRef context = UIGraphicsGetCurrentContext(); |
|
[image drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0]; |
|
|
|
CGContextSetFillColorWithColor(context, color.CGColor); |
|
CGContextSetBlendMode(context, kCGBlendModeSourceIn); |
|
CGContextSetAlpha(context, 1.0); |
|
|
|
CGRect rect = CGRectMake( |
|
CGPointZero.x, |
|
CGPointZero.y, |
|
image.size.width, |
|
image.size.height); |
|
CGContextFillRect(UIGraphicsGetCurrentContext(), rect); |
|
UIImage* tintedImage = UIGraphicsGetImageFromCurrentImageContext(); |
|
UIGraphicsEndImageContext(); |
|
|
|
return tintedImage; |
|
} |
|
|
|
@implementation UITextField (TintClearButton) |
|
|
|
- (void)tintClearImage |
|
{ |
|
for (UIView* view in self.subviews) { |
|
if (![view isKindOfClass:[UIButton class]]) |
|
continue; |
|
|
|
UIButton* button = (UIButton*)view; |
|
[button setImage:[self UITFC_normalClearImageForButton:button] forState:UIControlStateNormal]; |
|
[button setImage:[self UITFC_highlightClearImageForButton:button] forState:UIControlStateHighlighted]; |
|
} |
|
} |
|
|
|
- (UIImage*)UITFC_normalClearImageForButton:(UIButton*)button |
|
{ |
|
UIImage* image = [button imageForState:UIControlStateNormal]; |
|
return [self UITFC_getTintImage:image key:@"UITFC_tinted_clear_image_normal"]; |
|
} |
|
|
|
- (UIImage*)UITFC_highlightClearImageForButton:(UIButton*)button |
|
{ |
|
UIImage* image = [button imageForState:UIControlStateHighlighted]; |
|
return [self UITFC_getTintImage:image key:@"UITFC_tinted_clear_image_highlight"]; |
|
} |
|
|
|
- (UIImage*)UITFC_getTintImage:(UIImage*)image key:(NSString*)key |
|
{ |
|
UIImage* tintedImage = objc_getAssociatedObject(self, (__bridge const void*)(key)); |
|
|
|
if (tintedImage == nil) { |
|
tintedImage = UITFC_tintImage(image, self.tintColor); |
|
objc_setAssociatedObject(self, (__bridge const void*)(key), tintedImage, OBJC_ASSOCIATION_RETAIN_NONATOMIC); |
|
} |
|
|
|
return tintedImage; |
|
} |
|
|
|
@end |