在编辑时调整 UITextField 的大小

Resize UITextField on Edit

我的视图中有一个 UITextField,它有大小限制来布置它的位置。我想要发生的是当用户开始编辑字段时 UITextField 改变宽度。

我将视图控制器设置为该字段的委托,并且委托方法在这里工作

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

}

我需要知道的是我需要做什么来 textField 来改变它的宽度,因为我尝试过的所有方法都不起作用。

谢谢

您可以使用 .size 并将其设置为任何您想要的 CGSize

更多信息:https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGGeometry/index.html#//apple_ref/c/tdef/CGSize

你试过使用addTarget:action:forControlEvents吗? (下面我使用 Masonry 在代码中设置约束)

某处:

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

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

您可以做的是为文本字段的宽度限制设置一个出口。 在下面的例子中,我假设它的名字是 textFieldWidthConstraint

在您的 textFieldDidBeginEditing: 方法中添加:

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

你可以对高度做同样的事情。

希望对您有所帮助,如果您需要更多帮助,请告诉我。