Sunday, June 2, 2013

UITextField clearButtonMode example in Objective C (iOS).


UITextField clearButtonMode

Controls when the standard clear button appears in the text field.

@property(nonatomic) UITextFieldViewMode clearButtonMode

Discussion of [UITextField clearButtonMode]
The standard clear button is displayed at the right side of the text field as a way for the user to remove text quickly. This button appears automatically based on the value set for this property.

The default value for this property is UITextFieldViewModeNever.

UITextField clearButtonMode example.
cell = [tableView dequeueReusableCellWithIdentifier:@"CellNameIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"CellName" owner:self options:nil];
cell = cellName;
[cellName setAccessoryType:UITableViewCellAccessoryNone];
        //textfield in inside cellName
textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
}

Example of [UITextField clearButtonMode].

- (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);
}

UITextField clearButtonMode example.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    // Remove old instances of myTextField
    for (UIView *oldView in cell.contentView.subviews)
        [oldView removeFromSuperview];

    // Create my new text field
    UITextField *myTextField = [[UITextField alloc] initWithFrame:cell.contentView.bounds];
    [myTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [myTextField setBorderStyle:UITextBorderStyleRoundedRect];

    // Add the TextField to the content view
    [cell.contentView addSubview:myTextField];

    return cell;
}

End of UITextField clearButtonMode example article.