I'm using a subclass of UITextField to draw a " m3" string always at the end of my textfield, but something is not working. I know that the method is beeing called because i've tested it using a NSLog, what am I doing wrong?

My class:

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{

    NSString *strM3 = [[NSString alloc] initWithFormat:@" m³"];

    /// Make a copy of the default paragraph style
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    /// Set line break mode
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    /// Set text alignment
    paragraphStyle.alignment = NSTextAlignmentRight;

    NSDictionary *attributes = @{ NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue-Bold" size:12.0],
                                  NSParagraphStyleAttributeName:paragraphStyle};

    [strM3 drawInRect:rect withAttributes:attributes];

}
有帮助吗?

解决方案

UITextField has a lot of things drawn ontop of it's self. Background drawings are going to be covered up by all of those things. To test this you can programatically remove all subviews and see if your " m3" shows up.

for(UIView *subview in textField.subviews) [subview removeFromSuperview];

I think you are going to have to set a default text, then modify the input text whenever a new character is entered. Set up a UITextViewDelegate and overload the function shouldChangeCharactersInRange:

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  //Do some string manipulation in here to remove the "m3", then add the user's input, then replace the "m3"
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top