How to change the color of first letter of a textfields text
I have a textfield and starting letter of textfield's text is always a dollar sign.Now i need to change the color of dollar symbol so that dollar symbol and remaining text should be in different color. How can i do this??开发者_开发技巧 Any idea
Can't be done standard. Only one style is allowed in a UITextField.
Best idea: get rid of the $ in the UITextField, replace it with whitespace, then place a UILabel on top.
2nd best idea: subclass UITextField.
Edit:
UITextField
has a drawTextInRect:
method which is probably all you need to override.
Documented here. If you need more help, try googling or searching SO for how to subclass different UI classes, and get a feel for how to override draw methods (e.g. drawRect:
for UIView
)
Here's the @implementation of my LinethruLabel, a subclass of UILabel. It indicates a "scratched" item with a red linedrawn thru the text. In my case I call [super drawRect:rect];
and UILabel draws the text and background etc., but I'm not sure if whether you'll want to, so take it out if it's not working the way you want. So I guess you'll need to use some of the variations of drawAtPoint:withFont:
methods from NSString UIKit category.
@implementation LineThruUILabel
- (void)dealloc {
[super dealloc];
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
drawLine = NO;
}
return self;
}
- (void) setDrawLine:(BOOL) newValue
{
if( drawLine != newValue ){
drawLine = newValue;
[self setNeedsDisplay];
}
}
- (CGSize) calculateLineWidth
{
NSString *newText = self.text;
CGFloat actualFontSize;
CGFloat width = self.frame.size.width;
CGSize size = [newText sizeWithFont: self.font minFontSize:self.minimumFontSize
actualFontSize:&actualFontSize
forWidth:width
lineBreakMode:self.lineBreakMode ];
return size;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGFloat horizOffset = 0.0;
if( drawLine ){
CGSize lineSize = [self calculateLineWidth];
CGFloat offset = 1.0;
// Drawing code
CGContextRef ctx = UIGraphicsGetCurrentContext();
//CGFloat w = rect.size.width;
CGFloat h = rect.size.height;
// just match the color and size of the horizontal line
CGContextSetRGBStrokeColor(ctx, 1.0, 0.0, 0.0, 1.0);
CGContextSetLineWidth(ctx, 2.0);
CGContextMoveToPoint(ctx, horizOffset , h/2 + offset );
CGContextAddLineToPoint(ctx, lineSize.width + horizOffset + 1.0, h/2 + offset);
CGContextStrokePath(ctx);
}
}
精彩评论