循环并编辑UITextField占位符不起作用

时间:2016-01-28 14:06:39

标签: ios objective-c uiscrollview uitextfield

我有一个UIView,在UIVIew内我添加了UIScrollView,其中包含另一个UIView和一个UITextFields列表。我使用以下代码尝试循环遍历所有视图并选择UITextfields。问题是虽然循环正在发生但它找不到任何UITextfields

- (void)styleUITextFields {

for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)view;

        // Do whatever you want with the text field.
    }

}

这是我将UIScollView添加到UIView

的方法
- (void)addForm {

[self styleSegmentController];
[self styleUITextFields];

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

[self.scrollViewForm setContentSize:CGSizeMake(screenWidth, self.scrollViewForm.frame.size.height)];
[self.scrollViewForm setFrame:CGRectMake(0, 56, screenWidth, screenHeight - 56)];

[self.view addSubview:self.scrollViewForm];

}

有关为什么这可能不起作用的任何建议。

2 个答案:

答案 0 :(得分:1)

 - (void)styleUITextFields:(UIView*) view {

    for (UIView *subview in [view subviews]) {
        if ([subview isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)view;

            // Do whatever you want with the text field.
        } else { // look insde the subview for more views.
           [self styleUITextFields: subview];
         }

    }


- (void)addForm {

    [self styleSegmentController];
    [self styleUITextFields: self.view];

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;

    [self.scrollViewForm setContentSize:CGSizeMake(screenWidth, self.scrollViewForm.frame.size.height)];
    [self.scrollViewForm setFrame:CGRectMake(0, 56, screenWidth, screenHeight - 56)];

    [self.view addSubview:self.scrollViewForm];

}

答案 1 :(得分:1)

您的视图层次结构似乎是 self.view - > UIScrollView - > UIView - > UITextFields 。在这种情况下,UITextField上的for循环不会为您提供UITextField,因为它们不是self.view的直接子视图。

您应该迭代子视图的子视图,直到找到- (void)styleUITextFieldsInSubviewsOfView:(UIView *)view { // Get the subviews of the view NSArray *subviews = [view subviews]; // Return if there are no subviews if ([subviews count] == 0) return; for (UIView *subview in subviews) { if ([subview isKindOfClass:[UITextField class]]) { // Do whatever you want with the text field. } else { // Iterate the subviews of subview [self styleUITextFieldsInSubviewsOfView:subview]; } } } ,然后根据需要修改它们。

这可以通过

完成
self.view

最初传递[self styleUITextFields];来调用此方法。 因此,您可以代替[self styleUITextFieldsInSubviewsOfView:self.view]; 致电

{{1}}