【问题标题】:How can I perform a check on all check UITextField's in if condition如何在 if 条件下对所有检查 UITextField 进行检查
【发布时间】:2016-03-02 05:05:42
【问题描述】:

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

【问题讨论】:

  • 您可以将所有文本字段作为超级视图的子视图进行循环。
  • 使用 IBoutletcollection ,很容易查到
  • @Nishant 听起来不是一个好主意,因为必须仅对特定的 UITextField 执行检查。
  • 你也可以试试这个[self.view viewWithTag:33]; 你必须为所有的文本字段设置标签。并避免 0。

标签: ios objective-c uitextfield


【解决方案1】:

首先你要确保所有 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;
            }];
        }

    }

【讨论】:

  • 这对我很有帮助,你能帮我将 UITextfield 设置为活动状态吗,对不起,我是新手。
  • 更新了我的答案,希望对你有帮助
  • 是否有CGRectContainsRect 的替代方案,因为我的viewableAreaFrame 必须是减去keyboardSie.height 的框架,当我直接这样做时,我用double 初始化CGRect。 (错误)
  • 再次更新我的答案,计算有效的 viewableAreaFrame
  • 我开始工作了,我首先计算了 viewableAreaFrame 的高度并将其存储在 CGFloat 中,然后使用该高度创建了 CGRect。在此之后,if 表达式按预期工作。
猜你喜欢
  • 2022-10-04
  • 2016-09-24
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多