如何从子视图中删除动态 UITextField

How to remove Dynamic UITextField from Subview

如何从滚动子视图中删除 UITextField 的数组,最初当我调用 API 时,我根据在我的视图中创建动态 UITextFiled 的计数得到一些数组值,但我知道如何删除子视图

这里是我的示例代码:

// NSArray *strings;
// UIScrollView *scrollView;
// NSMutableArray *textFields;

self.textFields = [NSMutableArray array];

const CGFloat width = 320;
const CGFloat height = 31;
const CGFloat margin = 0;
CGFloat y = 0;

for(NSString *string in strings) {
UITextField *textField = [[UITextField alloc] 
initWithFrame:CGRectMake(0, y, width, height)];
textField.delegate = self;
textField.text = string;

[scrollView addSubview:textField];
[textFields addObject:textField];
[textField release];

y += height + margin;
}

scrollView.contentSize = CGSizeMake(width, y - margin);

如果您想从您的视图中删除该文本字段,那么您只需从您的父视图中删除该文本字段即可。

[yourtextfield removeFromSuperView];
scrollView.subViews.forEach({textField in
            if textField is UITextField , textField.tag == XX {
                textField.removeFromSuperView()
            }
        })

添加标签,然后使用循环删除任何文本视图

for (UITextView *i in scrollView){
    if([i isKindOfClass:[UITextView class]]){
        UITextView *tv = (UITextView *)i;
        if(tv.tag == 1){ // Whatever textview want to remove add tag here
            /// Write your code
            [tv removeFromSuperview];
        }
    }
}

首先,当您创建此动态时 textField 设置单个 tag,例如 101

for(NSString *string in strings) {
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, y, width, height)];
    textField.delegate = self;
    textField.text = string;
    //Set tag 101
    textField.tag = 101;
    [scrollView addSubview:textField];
    [textFields addObject:textField];
    [textField release];

    y += height + margin;
}

现在创建一个方法来删除所有这些动态文本字段。

- (void)removeAllDynamicTextFields {

    for(UIView *view in scrollView.subViews){
        if([view isKindOfClass:[UITextField class]] && view.tag == 101){
                [view removeFromSuperview];
            }
        }
    }
}