如何在視圖控制器中獲取所有UITextField的數組?獲取所有UITextField的數組
編輯:我不想將textfields硬編碼到數組中。我實際上想要從該委託的調用者的所有字段的委託內獲取列表。
如何在視圖控制器中獲取所有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