Showing posts with label UITextField. Show all posts
Showing posts with label UITextField. Show all posts

Sunday, June 2, 2013

UITextField UITextFieldViewModeAlways example in Objective C (iOS).


UITextField UITextFieldViewModeAlways

UITextFieldViewMode
Defines the times at which overlay views appear in a text field.

typedef enum {
UITextFieldViewModeNever,
UITextFieldViewModeWhileEditing,
UITextFieldViewModeUnlessEditing,
UITextFieldViewModeAlways
} UITextFieldViewMode;

Constants
UITextFieldViewModeNever
The overlay view never appears.
UITextFieldViewModeWhileEditing
The overlay view is displayed only while text is being edited in the text field.
UITextFieldViewModeUnlessEditing
The overlay view is displayed only when text is not being edited.
UITextFieldViewModeAlways
The overlay view is always displayed.

UITextField UITextFieldViewModeAlways example.
[textFieldAddress_ setLeftView:buttonBookmark_];
[textFieldAddress_ setLeftViewMode: UITextFieldViewModeAlways];
[textFieldAddress_ setRightView:buttonReloadAndCancel_];
[textFieldAddress_ setRightViewMode: UITextFieldViewModeUnlessEditing];
textFieldAddress_.clearButtonMode = UITextFieldViewModeWhileEditing;

Example of [UITextField UITextFieldViewModeAlways].
-(void) onEditing:(id)sender {
    if(![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }
}
- (BOOL)becomeFirstResponder{
    BOOL ret = YES ;
    ret = [super becomeFirstResponder] ;
    if( ret & ![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }

    return ret ;
}

UITextField UITextFieldViewModeAlways example.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    UITextField *searchField = nil;
    for (UIView *subview in controller.searchBar.subviews) {
        DebugLog(@"%@",[subview description]);
        if ([subview isKindOfClass:[UITextField class]]) {
            searchField = (UITextField *)subview;
            UIImageView *clearIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ClearIcon.png"]];
            searchField.rightView = clearIconView;
            searchField.rightViewMode = UITextFieldViewModeAlways;

            [clearIconView release];
            break;
        }
    }
}

End of UITextField UITextFieldViewModeAlways example article.

UITextField UITextFieldViewModeNever example in Objective C (iOS).


UITextField UITextFieldViewModeNever

UITextFieldViewMode
Defines the times at which overlay views appear in a text field.

typedef enum {
UITextFieldViewModeNever,
UITextFieldViewModeWhileEditing,
UITextFieldViewModeUnlessEditing,
UITextFieldViewModeAlways
} UITextFieldViewMode;

Constants
UITextFieldViewModeNever
The overlay view never appears.
UITextFieldViewModeWhileEditing
The overlay view is displayed only while text is being edited in the text field.
UITextFieldViewModeUnlessEditing
The overlay view is displayed only when text is not being edited.
UITextFieldViewModeAlways
The overlay view is always displayed.

UITextField UITextFieldViewModeNever example.
UITextField *f = [[[UITextField alloc] init] autorelease];
f.frame = CGRectMake(0, 0, 300, 44);
f.backgroundColor = [UIColor clearColor];
f.textColor = [UIColor whiteColor];

f.clearButtonMode = UITextFieldViewModeNever;

Example of [UITextField UITextFieldViewModeNever].
  UITextField *txfSearchField = [searchbar valueForKey:@"_searchField"];
[txfSearchField setBackgroundColor:[UIColor whiteColor]];
    [txfSearchField setLeftView:UITextFieldViewModeNever];
    [txfSearchField setBorderStyle:UITextBorderStyleRoundedRect];
    txfSearchField.layer.borderWidth = 8.0f;
    txfSearchField.layer.cornerRadius = 10.0f;
        txfSearchField.layer.borderColor = [UIColor clearColor].CGColor;

UITextField UITextFieldViewModeNever example.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifierForSection0 = @"Cell0";
    static NSString *CellIdentifierForSection1 = @"Cell1";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: [indexPath section] == 0 ? CellIdentifierForSection0 : CellIdentifierForSection1];
    if (cell == nil) {

        if ([indexPath section] == 0) { // Email & Password Section

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifierForSection0];
            cell.textLabel.text = @"Subject";

            UITextField *subject = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)];
            subject.adjustsFontSizeToFitWidth = YES;
            subject.textColor = [UIColor blackColor];
            if ([indexPath row] == 0) {
                subject.placeholder = @"Maths";
                subject.keyboardType = UIKeyboardTypeEmailAddress;
                subject.returnKeyType = UIReturnKeyNext;
            }
            subject.backgroundColor = [UIColor clearColor];
            subject.autocorrectionType = UITextAutocorrectionTypeNo;
            subject.autocapitalizationType = UITextAutocapitalizationTypeWords;
            subject.tag = 0;
            subject.clearButtonMode = UITextFieldViewModeNever;
            [cell.contentView addSubview:subject];
        } else {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifierForSection1];
            cell.textLabel.text = @"Task";

            UITextView *task = [[UITextView alloc] initWithFrame:CGRectMake(102, 0, 185, 40)];
            task.text = @"fasfashfjasfhasfasdjhasgdgasdhjagshjdgashjdgahjsdghjasgasdashgdgjasd";
            task.editable = NO;
            task.scrollEnabled = NO;
            task.userInteractionEnabled = NO;
            task.textColor = [UIColor colorWithRed: 62.0/255.0 green: 85.0/255.0 blue:132.0/255.0 alpha:1.0];
            task.backgroundColor = [UIColor clearColor];
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    return cell;
}

End of UITextField UITextFieldViewModeNever example article.

UITextField UITextBorderStyleRoundedRect example in Objective C (iOS).


UITextField UITextBorderStyleRoundedRect

UITextFieldBorderStyle
The type of border drawn around the text field.

typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
} UITextBorderStyle;

Constants
UITextBorderStyleNone
The text field does not display a border.
UITextBorderStyleLine
Displays a thin rectangle around the text field.
UITextBorderStyleBezel
Displays a bezel-style border for the text field. This style is typically used for standard data-entry fields.
UITextBorderStyleRoundedRect
Displays a rounded-style border for the text field.

UITextField UITextBorderStyleRoundedRect example.
int labelWidth = 100;
int labelHeight = 10;

_maxPriceField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, labelWidth, labelHeight)];
_maxPriceField.borderStyle     = UITextBorderStyleRoundedRect;
_maxPriceField.clearButtonMode = UITextFieldViewModeWhileEditing;

//_maxPriceField.font            = fieldFont;
//_maxPriceField.delegate        = self;
[self.view addSubview:_maxPriceField];

UITextField *secondField = [[UITextField alloc] initWithFrame:CGRectMake(10, 40, labelWidth, labelHeight + 10)];
secondField.borderStyle     = UITextBorderStyleRoundedRect;
[self.view addSubview:secondField];
[secondField release];

Example of [UITextField UITextBorderStyleRoundedRect].
    UITextField *mobileNumberField = [[UITextField alloc] initWithFrame:CGRectMake(10, 195, 300, 41)];
    mobileNumberField.delegate = self;
    mobileNumberField.layer.borderWidth = 1.0f;
    mobileNumberField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    mobileNumberField.
    mobileNumberField.borderStyle = UITextBorderStyleRoundedRect;
    [mobileNumberField.layer setCornerRadius:14.0f];
    mobileNumberField.placeholder = @"Mobile Number";
    [self.paymentsHomeView addSubview:mobileNumberField];

UITextField UITextBorderStyleRoundedRect example.
-(IBAction)addTextField:(id)sender{
    float x=previousTextField.frame.origin.x;
    float y=previousTextField.frame.origin.y+50;//get y from previous textField and add 10 or so in it.
    float w=previousTextField.frame.size.width;
    float h=previousTextField.frame.size.height;
    CGRect frame=CGRectMake(x,y,w,h);
    UITextField *textField=[[UITextField alloc] initWithFrame:frame];
    textField.placeholder = @"Enter User Name or Email";

    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.font = [UIFont systemFontOfSize:15];
    textField.autocorrectionType = UITextAutocorrectionTypeNo;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.returnKeyType = UIReturnKeyDone;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;

    [self.view addSubview:textField];
    previousTextField=textField;
}

End of UITextField UITextBorderStyleRoundedRect example article.

UITextField UITextBorderStyleBezel example in Objective C (iOS).


UITextField UITextBorderStyleBezel

UITextFieldBorderStyle
The type of border drawn around the text field.

typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
} UITextBorderStyle;

Constants
UITextBorderStyleNone
The text field does not display a border.
UITextBorderStyleLine
Displays a thin rectangle around the text field.
UITextBorderStyleBezel
Displays a bezel-style border for the text field. This style is typically used for standard data-entry fields.
UITextBorderStyleRoundedRect
Displays a rounded-style border for the text field.

UITextField UITextBorderStyleBezel example.
- (UITextField *)textFieldNormal
{
    if (textFieldNormal == nil)
    {
        CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
        textFieldNormal = [[UITextField alloc] initWithFrame:frame];

        textFieldNormal.borderStyle = UITextBorderStyleBezel;
        textFieldNormal.textColor = [UIColor blackColor];
        textFieldNormal.font = [UIFont systemFontOfSize:17.0];
        textFieldNormal.placeholder = @"";
        textFieldNormal.backgroundColor = [UIColor whiteColor];
        textFieldNormal.autocorrectionType = UITextAutocorrectionTypeNo;    // no auto correction support

        textFieldNormal.keyboardType = UIKeyboardTypeDefault;   // use the default type input method (entire keyboard)
        textFieldNormal.returnKeyType = UIReturnKeyDone;

        textFieldNormal.clearButtonMode = UITextFieldViewModeWhileEditing;  // has a clear 'x' button to the right

        textFieldNormal.tag = kViewTag;     // tag this control so we can remove it later for recycled cells

        textFieldNormal.delegate = self;    // let us be the delegate so we know when the keyboard's "Done" button is pressed

        // Add an accessibility label that describes what the text field is for.
        [textFieldNormal setAccessibilityLabel:NSLocalizedString(@"NormalTextField", @"")];
    }  
    return textFieldNormal;
}

Example of [UITextField UITextBorderStyleBezel].

UITextField *fourthField = [[UITextField alloc] initWithFrame:CGRectMake(10, 110, labelWidth, labelHeight + 30)];
fourthField.borderStyle     = UITextBorderStyleRoundedRect;
[self.view addSubview:fourthField];
[fourthField release];

UITextField *noRoundFirst = [[UITextField alloc] initWithFrame:CGRectMake(10, 160, labelWidth, labelHeight)];
noRoundFirst.borderStyle = UITextBorderStyleBezel;
noRoundFirst.backgroundColor = [UIColor whiteColor];
[self.view addSubview:noRoundFirst];
[noRoundFirst release];

UITextField UITextBorderStyleBezel example.
  self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 120.0f, 25.0f)];
  self.textField.returnKeyType = UIReturnKeyDone;
  self.textField.placeholder = @"Writer";
  self.textField.borderStyle=UITextBorderStyleBezel;
  [self.textField addTarget:self
                    action:@selector(textFieldDone:)
          forControlEvents:UIControlEventEditingDidEndOnExit];    
  [self addSubview: self.textField];

End of UITextField UITextBorderStyleBezel example article.

UITextField UITextBorderStyleLine example in Objective C (iOS).


UITextField UITextBorderStyleLine

UITextFieldBorderStyle
The type of border drawn around the text field.

typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
} UITextBorderStyle;

Constants
UITextBorderStyleNone
The text field does not display a border.
UITextBorderStyleLine
Displays a thin rectangle around the text field.
UITextBorderStyleBezel
Displays a bezel-style border for the text field. This style is typically used for standard data-entry fields.
UITextBorderStyleRoundedRect
Displays a rounded-style border for the text field.

UITextField UITextBorderStyleLine example.
UITextField *seedRateUnitTextField = [[UITextField alloc] initWithFrame:myRect];
seedRateUnitTextField.font = [UIFont fontWithName:textFieldFont size:textFieldFontSize];
seedRateUnitTextField.placeholder = @"Unit";
seedRateUnitTextField.borderStyle = UITextBorderStyleLine;
seedRateUnitTextField.backgroundColor = [UIColor whiteColor];
seedRateUnitTextField.textColor = [UIColor textFieldTextColor];
seedRateUnitTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
seedRateUnitTextField.layer.borderColor = [[UIColor textfieldBorderColor]CGColor];
seedRateUnitTextField.layer.borderWidth = 1.0f;
seedRateUnitTextField.leftView = paddingView;
seedRateUnitTextField.leftViewMode = UITextFieldViewModeAlways;
seedRateUnitTextField.rightView = rightPaddingView;
seedRateUnitTextField.rightViewMode = UITextFieldViewModeAlways;
seedRateUnitTextField.delegate = self;
seedRateUnitTextField.tag = 0;
[myScrollView addSubview:seedRateUnitTextField];
[self.dataSetDictionary setValue:seedRateUnitTextField forKey:@"seedRateUnitData"];

myRect = CGRectMake(200, ((4 * 40) + 140), 170, 30);

Example of [UITextField UITextBorderStyleLine].
UITextField *txtstate =[[UITextField alloc]init]; [txtstate setFrame:CGRectMake(10, 30,170, 30)];
txtstate.delegate=self;

txtstate.text=@"Fruits";

txtstate.borderStyle = UITextBorderStyleLine;

txtstate.background = [UIImage imageNamed:@"dropdownbtn.png"];

[txtstate setAutocorrectionType:UITextAutocorrectionTypeNo];
[self.view addSubview:txtstate];

UITextField UITextBorderStyleLine example.
textField.borderStyle = UITextBorderStyleLine;
textField.borderStyle = UITextBorderStyleNone;

End of UITextField UITextBorderStyleLine example article.

UITextField UITextBorderStyleNone example in Objective C (iOS).


UITextField UITextBorderStyleNone

UITextFieldBorderStyle
The type of border drawn around the text field.

typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect
} UITextBorderStyle;

Constants
UITextBorderStyleNone
The text field does not display a border.
UITextBorderStyleLine
Displays a thin rectangle around the text field.
UITextBorderStyleBezel
Displays a bezel-style border for the text field. This style is typically used for standard data-entry fields.
UITextBorderStyleRoundedRect
Displays a rounded-style border for the text field.

UITextField UITextBorderStyleNone example.
UITextField *tfText = [[UITextField alloc] initWithFrame:CGRectMake(65, 200, 200, 30)];
    tfText.backgroundColor = [UIColor colorWithRed:0.2 green:0.9 blue:0.5 alpha:0.3];      
    tfText.textAlignment = UITextAlignmentCenter;
    // Border Style None
    [tfText setBorderStyle:UITextBorderStyleNone];
    [self.view addSubview:tfText];
    [tfText release];

Example of [UITextField UITextBorderStyleNone].
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.bounds.size.width, 44.0f)];
[myTextField setBorderStyle:UITextBorderStyleNone];
[myTextField setPlaceholder:@"Title (optional)"];
[self.view addSubview:myTextField];

UIView *blackLineView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, myTextField.frame.origin.y + myTextField.frame.size.height, self.view.bounds.size.width, 3.0f)];
[blackLineView setBackgroundColor:[UIColor colorWithWhite:0.0f alpha:0.4f]];
[self.view addSubview:blackLineView];

UITextView *myTextView = [[UITextView alloc] initWithFrame:CGRectMake(0.0f, blackLineView.frame.origin.y + blackLineView.frame.size.height, self.view.bounds.size.width, 200.0f)];
[self.view addSubview:myTextView];

UITextField UITextBorderStyleNone example.
textField.borderStyle = UITextBorderStyleLine;
textField.borderStyle = UITextBorderStyleNone;

End of UITextField UITextBorderStyleNone example article.

UITextField placeholderRectForBounds example in Objective C (iOS).


UITextField placeholderRectForBounds

Returns the drawing rectangle for the text field’s placeholder text

- (CGRect)placeholderRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The computed drawing rectangle for the placeholder text.

Discussion of [UITextField placeholderRectForBounds]
You should not call this method directly. If you want to customize the drawing rectangle for the placeholder text, you can override this method and return a different rectangle.

If the placeholder string is empty or nil, this method is not called.

UITextField placeholderRectForBounds example.
subclassing UITextField will do the work:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
override the methods:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);//Return your desired x,y position and width,height
}

- (void)drawPlaceholderInRect:(CGRect)rect {
    //draw place holder.
 [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];

}
@end

Example of [UITextField placeholderRectForBounds].
// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
Here's how to override the method:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);
}
@end
However I don't think that's the method you want to override. I think this is what you're looking for:

@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Your drawing code.
}
@end

UITextField placeholderRectForBounds example.
- (CGRect)placeholderRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}

- (CGRect)editingRectForBounds:(CGRect)bounds
{
    return [self textRectForBounds:bounds];
}

End of UITextField placeholderRectForBounds example article.

UITextField rightViewRectForBounds example in Objective C (iOS).


UITextField rightViewRectForBounds

Returns the drawing location of the receiver’s right overlay view.

- (CGRect)rightViewRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The rectangle in which to draw the right overlay view.

Discussion of [UITextField rightViewRectForBounds]
You should not call this method directly. If you want to place the right overlay view in a different location, you can override this method and return the new rectangle.

UITextField rightViewRectForBounds example.
@interface MyTextField : UITextField
{
   //Declare your variable  here   
}
@end

@implementation MyTextFiled

// override rightViewRectForBounds method:
- (CGRect) rightViewRectForBounds:(CGRect)bounds{
    CGRect rightBounds = CGRectMake(bounds.origin.x + bounds.size.width + 30, 0, 45, 44);
    return rightBounds;
}

Example of [UITextField rightViewRectForBounds].

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(10,
                      0,
                      [self.label.text sizeWithFont:self.label.font constrainedToSize:CGSizeMake(MAX_LABEL_WIDTH, bounds.size.height)].width,
                      bounds.size.height);
}

- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    if (!self.showButton) { return CGRectZero; }

    return CGRectMake(bounds.size.width-BUTTON_WIDTH,
                      0,
                      BUTTON_WIDTH,
                      bounds.size.height);
}

End of UITextField rightViewRectForBounds example article.

UITextField leftViewRectForBounds example in Objective C (iOS).


UITextField leftViewRectForBounds

Returns the drawing rectangle of the receiver’s left overlay view.

- (CGRect)leftViewRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The rectangle in which to draw the left overlay view.

Discussion of [UITextField leftViewRectForBounds]
You should not call this method directly. If you want to place the left overlay view in a different location, you can override this method and return the new rectangle.

UITextField leftViewRectForBounds example.
@interface MyTextField : UITextField
{
   //Declare your variable  here   
}
@end

@implementation MyTextFiled

// override leftViewRectForBounds method:
- (CGRect)leftViewRectForBounds:(CGRect)bounds{
    CGRect leftBounds = CGRectMake(bounds.origin.x + 30, 0, 45, 44);
    return leftBounds;
}

Example of [UITextField leftViewRectForBounds].

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    return CGRectMake(10,
                      0,
                      [self.label.text sizeWithFont:self.label.font constrainedToSize:CGSizeMake(MAX_LABEL_WIDTH, bounds.size.height)].width,
                      bounds.size.height);
}

- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    if (!self.showButton) { return CGRectZero; }

    return CGRectMake(bounds.size.width-BUTTON_WIDTH,
                      0,
                      BUTTON_WIDTH,
                      bounds.size.height);
}

End of UITextField leftViewRectForBounds example article.

UITextField textRectForBounds example in Objective C (iOS).


UITextField textRectForBounds

Returns the drawing rectangle for the text field’s text.

- (CGRect)textRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The computed drawing rectangle for the label’s text.

Discussion of [UITextField textRectForBounds]
You should not call this method directly. If you want to customize the drawing rectangle for the text, you can override this method and return a different rectangle.

The default implementation of this method returns a rectangle that is derived from the control’s original bounds, but which does not include the area occupied by the receiver’s border or overlay views.

UITextField textRectForBounds example.
textField.bounds = [self editingRectForBounds:textField.bounds];
textField.bounds = [self textRectForBounds:textField.bounds];

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

Example of [UITextField textRectForBounds].
@interface UITextField (myCustomTextField)

@end

@implementation UITextField (myCustomTextField)

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end

UITextField textRectForBounds example.
Example of subclassing the UITextField:

- (CGRect)textRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

End of UITextField textRectForBounds example article.

UITextField editingRectForBounds example in Objective C (iOS).


UITextField editingRectForBounds

Returns the rectangle in which editable text can be displayed.

- (CGRect)editingRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The computed editing rectangle for the text.

Discussion of [UITextField editingRectForBounds]
You should not call this method directly. If you want to provide a different editing rectangle for the text, you can override this method and return that rectangle. By default, this method returns a region in the text field that is not occupied by any overlay views.

UITextField editingRectForBounds example.
textField.bounds = [self editingRectForBounds:textField.bounds];
textField.bounds = [self textRectForBounds:textField.bounds];

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect inset = CGRectMake(bounds.origin.x + 10, bounds.origin.y, bounds.size.width - 10, bounds.size.height);
    return inset;
}

Example of [UITextField editingRectForBounds].
@interface UITextField (myCustomTextField)

@end

@implementation UITextField (myCustomTextField)

- (CGRect)textRectForBounds:(CGRect)bounds {

    return CGRectInset(bounds, 10, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}

@end

UITextField editingRectForBounds example.
Example of subclassing the UITextField:

- (CGRect)textRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

End of UITextField editingRectForBounds example article.

UITextField drawPlaceholderInRect example in Objective C (iOS).


UITextField drawPlaceholderInRect

Draws the receiver’s placeholder text in the specified rectangle.

- (void)drawPlaceholderInRect:(CGRect)rect

Parameters
rect
The rectangle in which to draw the placeholder text.

Discussion of [UITextField drawPlaceholderInRect]
You should not call this method directly. If you want to customize the drawing behavior for the placeholder text, you can override this method to do your drawing.

By the time this method is called, the current graphics context is already configured with the default environment and text color for drawing. In your overridden method, you can configure the current context further and then invoke super to do the actual drawing or do the drawing yourself. If you do render the text yourself, you should not invoke super.

UITextField drawPlaceholderInRect example.
 @implementation CustomUITextFieldPlaceholder

- (void)drawPlaceholderInRect:(CGRect)rect {
    // Set colour and font size of placeholder text
    [[UIColor redColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];
}

@end

Example of [UITextField drawPlaceholderInRect].
subclassing UITextField will do the work:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end
override the methods:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);//Return your desired x,y position and width,height
}

- (void)drawPlaceholderInRect:(CGRect)rect {
    //draw place holder.
 [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];

}
@end

UITextField drawPlaceholderInRect example.
- (void) drawPlaceholderInRect:(CGRect)rect {

      [[UIColor redColor] setFill];
      [self.placeholder drawInRect:rect
                          withFont:self.font
                     lineBreakMode:UILineBreakModeTailTruncation
                         alignment:self.textAlignment];
    }

End of UITextField drawPlaceholderInRect example article.

UITextField clearButtonRectForBounds example in Objective C (iOS).


UITextField clearButtonRectForBounds

Returns the drawing rectangle for the built-in clear button.

- (CGRect)clearButtonRectForBounds:(CGRect)bounds

Parameters
bounds
The bounding rectangle of the receiver.

Return Value
The rectangle in which to draw the clear button.

Discussion of [UITextField clearButtonRectForBounds]
You should not call this method directly. If you want to place the clear button in a different location, you can override this method and return the new rectangle. Your method should call the super implementation and modify the returned rectangle’s origin only. Changing the size of the clear button may cause unnecessary distortion of the button image.

UITextField clearButtonRectForBounds example.
Subclass UITextField and override this method:

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.origin.x - 10, bounds.origin.y, bounds.size.width, bounds.size.height);
}

Example of [UITextField clearButtonRectForBounds].
@implementation TVUITextFieldWithClearButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
}

- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    return CGRectMake(bounds.size.width/2-20 , bounds.origin.y-3, bounds.size.width, bounds.size.height);
}

@end

End of UITextField clearButtonRectForBounds example article.

UITextField typingAttributes example in Objective C (iOS).


UITextField typingAttributes

The attributes to apply to new text being entered by the user.

@property(nonatomic,copy) NSDictionary *typingAttributes;

Discussion of [UITextField typingAttributes]
This dictionary contains the attribute keys (and corresponding values) to apply to newly typed text. When the text field’s selection changes, the contents of the dictionary are cleared automatically.

If the text field is not in editing mode, this property contains the value nil. Similarly, you cannot assign a value to this property unless the text field is currently in editing mode.

UITextField typingAttributes example.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.minimumLineHeight = 50.f;
mainTextView.typingAttributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];

Example of [UITextField typingAttributes].
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
        replacementString:(NSString *)string {
    NSDictionary* d = textField.typingAttributes;
    NSLog(@"%@", d);
    NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];
    // md[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleSingle);
    md[NSForegroundColorAttributeName] = [UIColor redColor];
    textField.typingAttributes = md;
    return YES;
}

UITextField typingAttributes example.
UITextView *textView = [self noteTextView];
NSMutableDictionary *typingAttributes = [[textView typingAttributes] mutableCopy];
[typingAttributes setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
NSLog(@"attributes after: %@", typingAttributes);
textView.attributedText = [[NSAttributedString alloc] initWithString:[textView text] attributes:typingAttributes];
NSLog(@"text view attributes after: %@", [textView typingAttributes]);

End of UITextField typingAttributes example article.

UITextField textColor example in Objective C (iOS).


UITextField textColor

The color of the text.

@property(nonatomic, retain) UIColor *textColor

Discussion of [UITextField textColor]
This property applies to the entire text string. The default value for this property is a black color. The value for the property can only be set to a non-nil value; setting this property to nil raises an exception.[UITextField textColor]

If you are using styled text in iOS 6 or later, assigning a new value to this property causes the text color to be applied to the entirety of the string in the attributedText property. If you want to apply the color to only a portion of the text, create a new attributed string with the desired style information and associate it with the text field.

UITextField textColor example.
@implementation PlaceholderChangingTextField

- (void) changePlaceholderColor:(UIColor*)color
{   
    // Need to place the overlay placeholder exactly above the original placeholder
    UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
    overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
    overlayPlaceholderLabel.opaque = YES;
    overlayPlaceholderLabel.text = self.placeholder;
    overlayPlaceholderLabel.textColor = color;
    overlayPlaceholderLabel.font = self.font;
    // Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
    [self.superview addSubview:overlayPlaceholderLabel];
    self.placeholder = nil;
}

Example of [UITextField textColor].
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //set color for text input
    textField.textColor = [UIColor blackColor];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    //set color for placeholder text
    textField.textColor = [UIColor redColor];
    return YES;
}

UITextField textColor example.
//On button action change color to red
-(void)btnAction
{
    // authentication for missing textfields
    if ([textField_firstName.text isEqualToString:@""])
    {
        textField_firstName.textColor=[UIColor redColor];
        textField_firstName.text=@"Enter First Name";
    }
}

// in the delegate method of UITextField change the following
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //match the following string with above string and change the string to empty string on textfield click
    if ([textField_firstName.text isEqualToString:@"Enter First Name" ])
    {
        textField_firstName.text=@"";
    }

    //change back to the text color you use
    textField_firstName.textColor=[UIColor blackColor];
}

End of UITextField textColor example article.

UITextField textAlignment example in Objective C (iOS).


UITextField textAlignment

The technique to use for aligning the text.

@property(nonatomic) NSTextAlignment textAlignment

Discussion of [UITextField textAlignment]
This property applies to the both the main text string and the placeholder string. The default value of this property is NSLeftTextAlignment.

If you are using styled text in iOS 6 or later, assigning a new value to this property causes the text alignment to be applied to the entirety of the string in the attributedText property. If you want to apply the alignment to only a portion of the text, create a new attributed string with the desired style information and associate it with the text field.

UITextField textAlignment example.
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    textField.textAlignment = NSTextAlignmentLeft ;
    return YES ;
}

Example of [UITextField textAlignment].
text = [[UITextField alloc] initWithFrame:CGRectMake(80.0, 8.0, 210.0, 30.0)];
text.clearsOnBeginEditing = YES;
text.delegate = self;
text.borderStyle = UITextBorderStyleRoundedRect;
text.textAlignment = UITextAlignmentCenter;

UITextField textAlignment example.
For VerticalAlignment.

textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
Centered both vertically and horizontally.

theTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
theTextField.textAlignment = UITextAlignmentCenter;

End of UITextField textAlignment example article.

UITextField text example in Objective C (iOS).


UITextField text

The text displayed by the text field.

@property(nonatomic, copy) NSString *text

Discussion of [UITextField text]
This string is nil by default.

In iOS 6 and later, assigning a new value to this property also replaces the value of the attributedText property with the same text, albeit without any inherent style attributes. Instead the text view styles the new string using the font, textColor, and other style-related properties of the class.

UITextField text example.
userName = [NSString stringWithFormat:@"%@", yournamefield.text];

Example of [UITextField text].
mytext = [ [ NSString alloc ] initWithUTF8String:"Init'd with utf8" ] ;
tf.text = mytext;
[mytext release];

UITextField text example.
you have to use the textfield delegate

-(void)textFieldDidEndEditing:(UITextField *)textField;
in this delegate make check like this

if ( [textField.text length] > 0 )
{
    // the text field is empty do your work
}

End of UITextField text example article.

UITextField rightViewMode example in Objective C (iOS).


UITextField rightViewMode

Controls when the right overlay view appears in the text field.

@property(nonatomic) UITextFieldViewMode rightViewMode

Discussion of [UITextField rightViewMode]
The default value for this property is UITextFieldViewModeNever.

UITextField rightViewMode example.
//add button to address bar
//UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)]
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateHighlighted];
refreshButton.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[refreshButton addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = refreshButton;
addressBar.rightViewMode = UITextFieldViewModeUnlessEditing;

Example of [UITextField rightViewMode].
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateHighlighted];
button.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[button addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = button;
addressBar.rightViewMode = UITextFieldViewModeAlways;

UITextField rightViewMode example.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    ...
    [self addTarget:self action:@selector(onEditing:) forControlEvents: UIControlEventEditingChanged]
    ...
}

-(void) onEditing:(id)sender {
    if(![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }
}
- (BOOL)becomeFirstResponder{
    BOOL ret = YES ;
    ret = [super becomeFirstResponder] ;
    if( ret & ![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }

    return ret ;
}
- (BOOL)resignFirstResponder
{
    BOOL ret = YES ;
    ret = [super resignFirstResponder] ;
    if( ret )
        self.rightViewMode = UITextFieldViewModeNever;
    return ret ;
}
- (void) clearText:(id)sender
{
    self.text = @"";
    self.rightViewMode = UITextFieldViewModeNever;
}

End of UITextField rightViewMode example article.

UITextField rightView example in Objective C (iOS).


UITextField rightView

The overlay view displayed on the right side of the text field.

@property(nonatomic, retain) UIView *rightView

Discussion of [UITextField rightView]
You can use the right overlay view to provide indicate additional features available for the text field. For example, you might display a bookmarks button in this location to allow the user to select from a set of predefined items.

The right overlay view is placed in the rectangle returned by the rightViewRectForBounds: method of the receiver. The image associated with this property should fit the given rectangle. If it does not fit, it is scaled to fit.[UITextField rightView]

If your overlay view does not overlap any other sibling views, it receives touch events like any other view. If you specify a control for your view, that control tracks and sends actions as usual. If an overlay view overlaps the clear button, however, the clear button always takes precedence in receiving events. By default, the right overlay view does overlap the clear button.

UITextField rightView example.
//add button to address bar
//UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
UIButton *refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)]
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
[refreshButton setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateHighlighted];
refreshButton.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[refreshButton addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = refreshButton;
addressBar.rightViewMode = UITextFieldViewModeUnlessEditing;

Example of [UITextField rightView].
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@\"RefreshIcon.png\"] forState:UIControlStateHighlighted];
button.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[button addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventTouchUpInside];
addressBar.rightView = button;
addressBar.rightViewMode = UITextFieldViewModeAlways;

UITextField rightView example.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    ...
    [self addTarget:self action:@selector(onEditing:) forControlEvents: UIControlEventEditingChanged]
    ...
}

-(void) onEditing:(id)sender {
    if(![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }
}
- (BOOL)becomeFirstResponder{
    BOOL ret = YES ;
    ret = [super becomeFirstResponder] ;
    if( ret & ![self.text isEqualToString:@""]){
        self.rightViewMode = UITextFieldViewModeAlways;
    }else{
        self.rightViewMode = UITextFieldViewModeNever;
    }

    return ret ;
}
- (BOOL)resignFirstResponder
{
    BOOL ret = YES ;
    ret = [super resignFirstResponder] ;
    if( ret )
        self.rightViewMode = UITextFieldViewModeNever;
    return ret ;
}
- (void) clearText:(id)sender
{
    self.text = @"";
    self.rightViewMode = UITextFieldViewModeNever;
}

End of UITextField rightView example article.

UITextField placeholder example in Objective C (iOS).


UITextField placeholder

The string that is displayed when there is no other text in the text field.

@property(nonatomic, copy) NSString *placeholder

Discussion of [UITextField placeholder]
This value is nil by default. The placeholder string is drawn using a 70% grey color.

UITextField placeholder example.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    textField.placeholder = @"Your Placeholdertext";
}

Example of [UITextField placeholder].
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   if ([textField.text isEqualToString:@""] || [[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0))
   {
       [textField setText:@""];
       textField.placeholder = @"Your Placeholdertext";
   }
}

UITextField placeholder example.
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"placeholder text here..."]) {
         textView.text = @"";
         textView.textColor = [UIColor blackColor]; //optional
    }
    [textView becomeFirstResponder];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"placeholder text here...";
        textView.textColor = [UIColor lightTextColor]; //optional
    }
    [textView resignFirstResponder];
}

End of UITextField placeholder example article.