如何按标题查找UIButton

时间:2013-04-28 06:53:51

标签: objective-c

我的UIView中有一个按钮。按钮不在某个数组中。

我想查看整个UIView(使用for循环)并按标题查找按钮,然后将其删除。

- (void)removeButtonByTitle:(NSString*)name
{
    for (buttons in view) {
        // find the button with the name "name" and remove it from the view 
    }
}

如果不将其名称/指针保存到数组中,我找不到办法。

4 个答案:

答案 0 :(得分:3)

通常最好使用tag属性。然后,您可以使用viewWithTag:方法找到按钮,如果您决定更改按钮标题或本地化您的应用,则无需调整代码。

如果你真的需要按标题找到一个按钮,你可以这样做:

NSString *buttonTitle = @"name";
UIButton *buttonWithTitle = nil;
for (UIButton *button in view.subviews) {
    if (![button isKindOfClass:[UIButton class]]) continue;
    if ([[button currentTitle] isEqualToString:buttonTitle]) {
        buttonWithTitle = button;
        break;
    }
}
//do something with the button...

答案 1 :(得分:1)

你可以这样做:

for (UIView *v in view.subviews)
    if ([v isKindOfClass:[UIButton class]] && [[(UIButton *)v currentTitle] isEqualToString:@""])
        //remove

但我必须说这听起来不是一个强大的解决方案,你的按钮标题可能会在本地化期间发生变化,或者对于不同的状态可能会有所不同。

答案 2 :(得分:1)

那样做:

- (void)removeButtonByTitle:(NSString *)name
{
  for (UIView *tempView in self.subviews)
    {
       if ([tempView isKindOfClass:[UIButton class]]) // make sure it's actually a UIButton
         { 
              UIButton *button = tempView;
              if ([button.titleLabel.text isEqualToString:name])  // compare the title
                 {
                    [button removeFromSuperview];
                 }
         }
    }
 }

答案 3 :(得分:0)

检查一下:

-(void)removeButtonWithTitle:(NSString*)titleString {
NSArray *subViews = [self.view subviews];
[subViews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if([obj isKindOfClass:[UIView class]]) {
        NSArray *subViewsArray = [(UIView*)obj subviews];
        for (int i=0; i<[subViewsArray count]; i++) {
            id subViewObj = [subViewsArray objectAtIndex:i];
            if([subViewObj isKindOfClass:[UIButton class]] && [[(UIButton*)subViewObj titleLabel].text isEqualToString:titleString]) {
                [subViewObj removeFromSuperview];
                *stop = YES;
                break;
            }
        }
    }
}];
}