我有一组按钮,我想在点击时显示按钮标题,并在再次点击时隐藏。这是我的代码,
- (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++;
}
}
}
}
但它在第一次点击时显示整个按钮标题,我想只显示点击的按钮标题。请帮助我在代码中做出哪些更改?
答案 0 :(得分: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];
}
}
答案 1 :(得分: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
答案 2 :(得分:0)
如果设置button.titlelabel.text=@"some string"
,它会在点击按钮时自动消失