如何检查所有检查UITextField的if条件

时间:2016-03-02 05:05:43

标签: ios objective-c uitextfield

我一直在寻找解决方案,但到目前为止尚未找到解决方案,请参考this的答案,我想知道是否有办法可以对所有UITextField执行检查,而不是有一个硬编码值,谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

首先确保所有textField都将其委托设置为self(表示你的viewController)

 Ex. [myTextField setDelegate:self];// you can also set the delegate in Storyboard or xib directly 

然后在类实现中添加一个实例变量,如 -

@implementation myViewController 
{ 
   UITextField *activeField; 
}

然后简单地实现如下方法

在textFieldShouldBeginEditing中,设置activeField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    activeField = textField; // HERE get reference of your active field
    return true;
}

为所有处理提供了一个非常好的方法

CGRectContainsRect

 if (!CGRectContainsRect(viewableAreaFrame, activeTextFieldFrame))
 {
     /*Scroll or move view up*/
 } 

在您的keyboardWillShow方法

中实现以下内容

EX。

 - (void)keyboardWillShow:(NSNotification *)notification
    {
        CGSize keyboardSize = [[[notification userInfo]      objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

float viewWidth = self.view.frame.size.width;
float viewHeight = self.view.frame.size.height;


CGRect viewableAreaFrame = CGRectMake(0.0, 0.0, viewWidth, viewHeight - keyboardHeight);

CGRect activeTextFieldFrame = [activeTextField frame];

        if (!CGRectContainsRect(viewableAreaFrame, activeTextFieldFrame))
        {
                 /*Scroll or move view up*/

            [UIView animateWithDuration:0.3 animations:^{
                CGRect f = self.view.frame;
                f.origin.y = -keyboardSize.height;
                self.view.frame = f;
            }];
        }

    }