我是 iPhone 应用程序开发的新手。在我的应用程序中,我使用的是 tableview。在 tableview 中,我使用了两个 uibuttons,一个是white color,另一个是 graycolor.如果我点击灰色按钮,它应该变成白色,同时另一个按钮应该变成灰色。
这是我的代码:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
ExampleCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=nil;
if(cell == nil)
{
cell = [[ExampleCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
if(indexPath.row == 0)
{
postbtn = [UIButton buttonWithType:UIButtonTypeCustom];
[postbtn setFrame:CGRectMake(0, 205, 160, 34)];
[postbtn setBackgroundColor:[UIColor whiteColor]];
[postbtn setTitle:[NSString stringWithFormat:@"%@ POST",[AppDelegate.profileDic objectForKey:@"posts"]] forState:UIControlStateNormal];
[postbtn.titleLabel setFont:[UIFont fontWithName:@"Verdana-Bold" size:10]];
[postbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[postbtn setTag:1001];
[postbtn addTarget:self action:@selector(reloadAction:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:postbtn];
likebtn = [UIButton buttonWithType:UIButtonTypeCustom];
[likebtn setFrame:CGRectMake(160, 205, 160, 34)];
[likebtn setBackgroundColor:[UIColor lightGrayColor]];
[likebtn setTitle:[NSString stringWithFormat:@"%@ LIKE",[AppDelegate.profileDic objectForKey:@"likes"]] forState:UIControlStateNormal];
[likebtn.titleLabel setFont:[UIFont fontWithName:@"Verdana-Bold" size:10]];
[likebtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[likebtn setTag:1002];
[likebtn addTarget:self action:@selector(reloadAction:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:likebtn];
}
)};
-(void)reloadAction:(id)sender
{
if ([sender tag] == 1001)
{
[postbtn setBackgroundColor:[UIColor whiteColor]];
[likebtn setBackgroundColor:[UIColor lightGrayColor]];
AppDelegate.selectedTab=1;
[profiletableview reloadData];
}
if ([sender tag] == 1002)
{
[postbtn setBackgroundColor:[UIColor lightGrayColor]];
[likebtn setBackgroundColor:[UIColor whiteColor]];
AppDelegate.selectedTab=2;
[self likewebservice];
[profiletableview reloadData];
}
}
有什么办法可以改变uibutton的背景色
最佳答案
问题是您在按下按钮后立即重新加载表格,包括:
[profiletableview reloadData];
在您的 reloadAction:
方法中。通过这样做,您只是将颜色重置为最初在 tableView:cellForRowAtIndexPath:
中定义的颜色。取出那条线,它应该可以工作。
编辑:
如果您需要能够重新加载表中的数据,您可能不应该在 tableView:cellForRowAtIndexPath:
方法中初始化 UIButton(或者至少,您不应该初始化第一次加载后重复 UIButtons)。您最好在 viewDidLoad 方法中初始化您的 UIButtons,以便在加载表之前对它们进行初始化,然后,正如您已经完成的那样,在 tableView:cellForRowAtIndexPath:
期间将 UIButtons 添加到单元格中,并且在 reloadAction:
期间更改按钮颜色和值。我可能是错的,但在这种情况下,您可能仍然不需要在 reloadAction:
期间重新加载表格,因为您直接更改按钮,也可以直接更改按钮标题同样的方法;但是,在不弄乱按钮的情况下可以选择重新加载表格通常是件好事。
编辑#2:
此外,如果该行保持静态,您可以使用 reloadRowsAtIndexPaths:withRowAnimation 仅重新加载必要的行,或者如 KIDdAe 所说,进行完整的表格重新加载,但仅在 cell==nil 时才将按钮添加到单元格。
关于ios - 如何在 iPhone 中单击操作更改两个 uibutton 的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20638512/