-
-
Save kwigbo/a4ef7d542fe46b5e6ff1 to your computer and use it in GitHub Desktop.
Fix for UITextField attributedPlaceholder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -- .h | |
extern const NSString *PLACEHOLDER_BASELINE_ATTRIBUTE; | |
extern const NSString *PLACEHOLDER_LEFT_ATTRIBUTE; | |
/** | |
* In this UITextField subclass, the attributedPlaceholder text actually works. | |
* | |
* @author Jed Laudenslayer | |
*/ | |
@interface WorkingTextField : UITextField | |
//! The color for the attributed text. | |
@property (nonatomic, strong) UIColor *placeholderTextColor; | |
@end | |
// -- .m | |
#import "WorkingTextField.h" | |
const NSString *PLACEHOLDER_BASELINE_ATTRIBUTE = @"baseline_attribute"; | |
const NSString *PLACEHOLDER_LEFT_ATTRIBUTE = @"left_attribute"; | |
@implementation WorkingTextField | |
{ | |
NSAttributedString *realAttributedPlaceholder_; | |
} | |
@synthesize placeholderTextColor = placeholderTextColor_; | |
- (void)setAttributedPlaceholder:(NSAttributedString *)attributedPlaceholder | |
{ | |
[super setAttributedPlaceholder:attributedPlaceholder]; | |
realAttributedPlaceholder_ = attributedPlaceholder; | |
} | |
- (void)drawPlaceholderInRect:(CGRect)rect | |
{ | |
if (realAttributedPlaceholder_ != nil) | |
{ | |
__block NSAttributedString *placeholder = realAttributedPlaceholder_; | |
__block CGFloat lastX = 0.0; | |
[placeholder enumerateAttributesInRange:NSMakeRange(0, placeholder.length) | |
options:0 | |
usingBlock:[^(NSDictionary *attrs, NSRange range, BOOL *stop) { | |
CGFloat baseline = [attrs[PLACEHOLDER_BASELINE_ATTRIBUTE] floatValue]; | |
CGFloat leftOffset = [attrs[PLACEHOLDER_LEFT_ATTRIBUTE] floatValue]; | |
NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] | |
initWithAttributedString:[placeholder | |
attributedSubstringFromRange:range]]; | |
if (placeholderTextColor_ != nil && [attrs objectForKey:NSForegroundColorAttributeName] == nil) | |
{ | |
[subString addAttribute:NSForegroundColorAttributeName value:placeholderTextColor_ range:NSMakeRange(0, subString.length)]; | |
} | |
CGSize stringSize = subString.size; | |
[subString drawAtPoint:CGPointMake(lastX + leftOffset, (rect.origin.y + rect.size.height) - (stringSize.height + baseline))]; | |
lastX += stringSize.width; | |
} copy]]; | |
} | |
else | |
{ | |
[super drawPlaceholderInRect:rect]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment