如何在视图控制器中获取所有UITextField的数组?
编辑:我不想将文本字段硬编码为数组。我实际上想要从该委托的调用者的所有字段的委托中获取列表。
答案 0 :(得分:16)
搜索所有子视图的子视图的递归实现:(这样你就可以捕获uiscrollview中嵌入的文本字段等)
-(NSArray*)findAllTextFieldsInView:(UIView*)view{
NSMutableArray* textfieldarray = [[[NSMutableArray alloc] init] autorelease];
for(id x in [view subviews]){
if([x isKindOfClass:[UITextField class]])
[textfieldarray addObject:x];
if([x respondsToSelector:@selector(subviews)]){
// if it has subviews, loop through those, too
[textfieldarray addObjectsFromArray:[self findAllTextFieldsInView:x]];
}
}
return textfieldarray;
}
-(void)myMethod{
NSArray* allTextFields = [self findAllTextFieldsInView:[self view]];
// ...
}
答案 1 :(得分:3)
如果您知道需要包含所有NSArray
的{{1}},那么为什么不将它们添加到数组中呢?
UITextField
如果您使用的是笔尖,请使用NSMutableArray *textFields = [[NSMutableArray alloc] init];
UITextField *textField = [[UITextField alloc] initWithFrame:myFrame];
[textFields addObject:textField]; // <- repeat for each UITextField
IBOutletCollection
然后将所有@property (nonatomic, retain) IBOutletCollection(UITextField) NSArray *textFields;
连接到该数组
答案 2 :(得分:1)
- 使用以下代码获取包含View上所有UITextField文本值的数组:
NSMutableArray *addressArray=[[NSMutableArray alloc] init];
for(id aSubView in [self.view subviews])
{
if([aSubView isKindOfClass:[UITextField class]])
{
UITextField *textField=(UITextField*)aSubView;
[addressArray addObject:textField.text];
}
}
NSLog(@"%@", addressArray);
答案 3 :(得分:1)
extension UIView
{
class func getAllSubviewsOfType<T: UIView>(view: UIView) -> [T]
{
return view.subviews.flatMap { subView -> [T] in
var result = UIView.getAllSubviewsOfType(view: subView) as [T]
if let view = subView as? T {
result.append(view)
}
return result
}
}
func getAllSubviewsWithType<T: UIView>() -> [T] {
return UIView.getAllSubviewsOfType(view: self.view) as [T]
}
}
如何与文本字段一起使用:
let textFields = self.view.getAllSubviewsWithType() as [UITextField]
答案 4 :(得分:-1)
您可以遍历控制器视图的子视图。
以下是 粗略 示例:
NSMutableArray *arrOfTextFields = [NSMutableArray array];
for (id subView in self.view.subviews)
{
if ([subView isKindOfClass:[UITextField class]])
[arrOfTextFields addObject:subView];
}
答案 5 :(得分:-1)
编辑没有全局变量的递归(仅适用于Tim)
-(NSArray*)performUIElementSearchForClass:(Class)targetClass onView:(UIView*)root{
NSMutableArray *searchCollection = [[[NSMutableArray alloc] init] autorelease];
for(UIView *subview in root.subviews){
if ([subView isKindOfClass:targetClass])
[searchCollection addObject:subview];
if(subview.subviews.count > 0)
[searchCollection addObjectsFromArray:[self performUIElementSearchForClass:targetClass onView:subview]];
}
return searchCollection;
}