Glenn Flanagan
Glenn Flanagan

Reputation: 61

Resize UITextField on Edit

I have a UITextField in my view which has size constraints to lay out it's position. What I want to happen is for the UITextField to change in width when a user begins to edit the field.

I have the view controller set as a delegate for the field and I have the delegate method working here

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"Search Field is being edited");

}

What I need to know is what do I need to do to textField to make it's width change as everything I've tried doesn't work.

Thanks

Upvotes: 0

Views: 322

Answers (3)

Jad Feitrouni
Jad Feitrouni

Reputation: 637

What you could do is set an outlet for the width constraint of your textfield. In the following example i am gonna suppose its name is textFieldWidthConstraint

in your textFieldDidBeginEditing: method add this:

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    // no animation
    self.textFieldWidthConstraint.constant = newWidth;

    // animation
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.3 animations:^
    {
        self.textFieldWidthConstraint.constant = newWidth;
        [self.view layoutIfNeeded];
    }
}

you could do the same thing for the height.

Hope that helps, let me know if you need more help.

Upvotes: 1

dOM
dOM

Reputation: 555

have u tried using addTarget:action:forControlEvents? (below i use Masonry to setup constraints in code)

somewhere:

UITextField *textField = [[UITextField alloc] init];
[textField setBackgroundColor:kBlackColor];
[textField setTextColor:kWhiteColor];
[textField setText:@"TEXT"];
[self.view addSubview:textField];
[textField addTarget:self action:@selector(textFieldDidChange:) UIControlEventEditingChanged];
[textField mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(self.view.mas_centerX);
    make.centerY.equalTo(self.view.mas_centerY);
    make.width.equalTo(@100);
    make.height.equalTo(@20);
}];

and

- (void)textFieldDidChange:(UITextField *)textField
{
    CGSize size = [textField sizeThatFits:CGSizeMake(CGFLOAT_MAX, textField.frame.size.height)];
    CGFloat minimumWidth = MAX(100, size.width);

    [textField mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(minimumWidth));
    }];

    [self.view layoutIfNeeded];
}

Upvotes: 1

djkevino
djkevino

Reputation: 364

You can use the .size for it and setting it to a CGSize of whatever you want.

More info: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGGeometry/index.html#//apple_ref/c/tdef/CGSize

Upvotes: -1

Related Questions