获取所有UITextField的数组
如何在视图控制器中获取所有UITextField的数组?获取所有UITextField的数组
编辑:我不想将textfields硬编码到数组中。我实际上想要从该委托的调用者的所有字段的委托内获取列表。
递归执行搜索所有子视图子视图:(此你抓住嵌入在uiscrollview中的textfields的方式,等等)
-(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]];
// ...
}
这不是'if([x respondsToSelector:@selector(subviews)]){''冗余为'-subviews'返回'@property(非原子,只读,复制)NSArray * subviews'。因此,该数组中的任何项目将是'UIView'或一个子类或'UIView'类型,它响应'@selector(subviews)' – 2012-01-13 23:43:55
我只是很不稳定,知道类 - 如果某些骨头以'subviews'包含非'UIView'-继承的对象,并因此不响应'@selector(subviews)'的方式来区分'UIView'会怎么样? – Tim 2012-01-13 23:59:20
重写该方法并添加非'UIView'没有意义 - 如果用户确实很聪明,他们很可能知道他们为什么要这么做,以及它可能涉及哪些风险。至少这是人们希望的;) – 2012-01-14 00:20:59
您可以循环控制器视图的子视图。
这里有一个粗糙例如:
NSMutableArray *arrOfTextFields = [NSMutableArray array];
for (id subView in self.view.subviews)
{
if ([subView isKindOfClass:[UITextField class]])
[arrOfTextFields addObject:subView];
}
这不会捕获其他视图中嵌入的UITextFields。 – 2012-01-13 22:13:42
编辑递归没有全局变量(只为添)
-(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;
}
如果你知道你需要一个NSArray
包含所有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;
然后所有的UITextField
的连接到阵列
- 使用下面的代码获取数组,其中包含的文本值所有显示在视图上的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);
创建它们时将它们添加到数组??? – 2012-01-13 22:25:00
请注意,委托不包含对文本字段的引用,这是相反的方式,无法单独从委托中查找字段。 http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html – Tim 2012-01-17 19:46:52