dotnet-practitioner dotnet-practitioner - 4 months ago 22
iOS Question

add button to uitextfield

When I click inside text box, How can I add plus button to UITextField as shown in the following screen? When this button is clicked it would launch iPhone contact application. I would very much appreciate any code example. Thanks

enter image description here

Answer

Use following method for add UIButton

[self.txtField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

- (BOOL) textFieldDidChange:(UITextField *)textField
{
    UIButton *btnColor = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnColor addTarget:self action:@selector(btnColorPressed:) forControlEvents:UIControlEventTouchUpInside];
    btnColor.frame = CGRectMake(self.txtTag.bounds.size.width - 50, 5, 25, 25);
    [btnColor setBackgroundImage:[UIImage imageNamed:@"PaintPickerButton.png"] forState:UIControlStateNormal];
    [self.txtTag addSubview:btnColor];

    return YES;
}

Or Write

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
    // self.scrollView.frame = CGRectMake(0, 35, self.view.bounds.size.width, self.view.bounds.size.height - 250);
    [UIView commitAnimations];

    UIButton *btnColor = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnColor addTarget:self action:@selector(btnColorPressed:) forControlEvents:UIControlEventTouchUpInside];
    btnColor.frame = CGRectMake(150, 5, 25, 25);
    [btnColor setBackgroundImage:[UIImage imageNamed:@"PaintPickerButton.png"] forState:UIControlStateNormal];
    [self.txtField addSubview:btnColor];

    return YES;
}