1

我有一组按钮,我想在单击时显示按钮标题并在再次单击时隐藏。这是我的代码,

 - (IBAction)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int index = button.tag;
[temp replaceObjectAtIndex:index withObject:@"1"];
[self showing];
}


 -(void)showing
 {
 UIButton *button = nil;
 NSString *name = nil;
 int i = 0;
 for(UIView *view in self.view.subviews)
 {
    if([view isKindOfClass:[UIButton class]])
    {
        button= (UIButton *)view;
        if(button.tag >= 1 && button.tag <= 16)
        {
            name = [NSString stringWithFormat:@"%@",[texts objectAtIndex:i]];
            if ([[temp objectAtIndex:i] isEqualToString:@"1"])
            {
                [button setTitle:name forState:UIControlStateNormal];
                NSLog(@"current  name :%@",name);
            }
            else
            {
                [button setTitle:@"" forState:UIControlStateNormal];
            }
            i++;
        }
    }
 }
 }

但它会在第一次单击时显示整个按钮标题,我只想显示单击的按钮标题。请帮助我应该对我的代码进行哪些更改?

4

3 回答 3

2
- (IBAction)buttonAction:(id)sender
{    
    UIButton *button = (UIButton *)sender;
    if (![button.titleLabel.text isEqualToString:@""]) {

        [button setTitle:@"" forState:UIControlStateNormal];
    }
    else {
         // set title same like as you set in showing method
        [button setTitle:GiveTitleHere forState:UIControlStateNormal];        
    }
}
于 2012-11-05T10:29:05.020 回答
1

我假设您已经设置了一个数组temp,它是视图控制器中的类级别变量。我建议给它一个合适的名字,比如textArray

因此,请尝试以下操作:

-(IBAction)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    int index = button.tag;
    [self showing:index]; //now, this method accepts a parameter.
}

-(void) showing:(NSInteger)index
{
    UIButton* btn = nil;
    index = index - 1; //this is because the array index start from 0, 
                            //but tags have to be more than 0 to be valid
    NSArray* subViewArray = [self.view subviews];

    NSInteger i = 0;

    for (UIView *view in subViewArray) 
    {
        if ([view isKindOfClass:[UIButton class]]) 
        {
            btn = (UIButton*) view;
            NSString* text;
            if (i == index) {
                text = [self.textArray objectAtIndex:i]; //put the array that you are using
                self.previousButtonTag = i; //make a class variable

            }
            else {
                text = @"";
            }
                //NEW EDIT 

                /*  1.fetch the title from self.textArray for "self.previousButtonTag"  
                    2.the title for the current button is there in "text" variable
                    3.compare both the strings and do things as per your liking
                */

            i++;
            [btn setTitle:text forState:UIControlStateNormal];
        }// end of IF
    } //end of FOR
} //end of METHOD
于 2012-11-05T12:02:44.857 回答
0

如果你设置button.titlelabel.text=@"some string"它会在按钮点击时自动消失

于 2012-11-05T10:28:30.007 回答