我的UIButton
视图中只有一个UIViewController
。我还在主视图中的subview
中还有十个。我想找到所有这些按钮。到目前为止,我有:
-(void)findAllButtons{
for(UIView *view in self.view.subviews) {
if ([view isKindOfClass:[myButton class]]){
NSLog(@"found a button!");
}
}
}
虽然只找到了单个按钮而不是其他十个按钮。这是为什么?不应该迭代每一个subview
,然后找到它们吗?
答案 0 :(得分:2)
persist
答案 1 :(得分:1)
使用像这样的Objective-C块的递归函数将查找给定子类类型的所有视图,如给定视图的视图层次结构中的测试块中指定的那样:
NSMutableArray *marrAllButtons = [NSMutableArray new];
BOOL (^viewTest)(UIView*) = ^BOOL(UIView* viewToTest) {
return [view isKindOfClass:[UIButton class]];
};
void(^viewEnumerator)(UIView*) = ^(UIView* outerView){
for (UIView *view in outerView.subviews)
{
if (viewTest(view))
{
[marrAllButtons addObject:view];
}
else
{
viewEnumerator(view);
}
}
};
viewEnumerator(self.view);
NSLog(@"All Buttons %@", marrAllButtons);
答案 2 :(得分:1)
只需几行代码
-(void)findAllButtons {
[self findButtonsInSubviews:self.view.subviews];
}
- (void)findButtonsInSubviews:(NSArray *)subviews {
for(UIView *view in subviews) {
if ([view isKindOfClass:[UIButton class]]){
NSLog(@"found a button!");
} else {
[self findButtonsInSubviews:view.subviews];
}
}
}
答案 3 :(得分:0)
- (NSMutableArray *)buttonsInView:(UIView *)view
{
NSArray *subviews = view.subviews;
NSMutableArray *buttons = [NSMutableArray array];
for (UIView *subview in subviews)
{
if ([subview isKindOfClass:[UILabel class]])
{
[buttons addObject:subview];
}
else if(subview.subviews)
{
[buttons addObjectsFromArray:[self buttonsInView:subview]];
}
}
return buttons;
}
答案 4 :(得分:0)
如果您的所有按钮已经在 self.view(主视图)中,您的方法是正确的。
设置标记 所有按钮以检查并确保所有按钮位于主视图。我希望这会奏效。
-(void)findAllButtons{
for(UIView *view in self.view.subviews) {
if ([view isKindOfClass:[myButton class]]){
UIButton *button = (UIButton*)view;
NSLog(@"found a button with tag:%d",button.tag);
}
}
}
答案 5 :(得分:0)
for(UIView * subView in view.subviews) // here write Name of you ScrollView.
{
// NSLog(@"test %@", [subView class]);
if([subView isKindOfClass:[UIButton class]])
{
UIButton *button = (UIButton*)subView;
[button setSelected:NO] ;
NSString *s1;
s1 = @",";
s1 = [s1 stringByAppendingString:[NSString stringWithFormat:@"%@",button.titleLabel.text ]];
s1 = [s1 stringByAppendingString:[NSString stringWithFormat:@"%@",@"," ]];
NSRange range = [temp_Colors_Name_comma rangeOfString:s1 ];
if(range.location == NSNotFound)
{
}
else
{
[button setSelected:YES];
}
}
}