gpt4 book ai didi

ios - 如何使 uitableview 的部分标题中的按钮保持选中状态

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:51 25 4
gpt4 key购买 nike

我有一个按钮,如果它被选中,我想更改背景图像。我这里的代码有效,但如果我再次向上和向下滚动,它将变为未选中状态。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 33)];
UILabel *sectionHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
sectionHeaderLabel.text = [NSString stringWithFormat:@"Section %i",section+1];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(200, 5, 42, 20)];
[button setBackgroundImage:[UIImage imageNamed:@"unselected_image"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"selected_image"] forState:UIControlStateSelected];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[sectionHeader addSubview:button];
return sectionHeader;
}

- (void)buttonPressed:(id)sender {
UIButton *allButton = (UIButton*)sender;
allButton.selected = !allButton.selected;
}

最佳答案

1) 在您的 ViewDidLoad 中创建一个图像名称数组。该数组会跟踪您照片的名称,无论照片是否被点击。

- (void)viewDidLoad
{
//this array is just an example, loop and add items to the array for the number of sections you want
//in this example there are 5 sections with 5 images
imageNameArray = [[NSMutableArray alloc] initWithObjects:@"unselected_image", @"unselected_image", @"unselected_image", @"unselected_image", @"unselected_image", nil];
}

2) 你的viewForHeaderInSection

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 33)];
UILabel *sectionHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
sectionHeaderLabel.text = [NSString stringWithFormat:@"Section %i",section+1];
button = [[UIButton alloc] initWithFrame:CGRectMake(200, 5, 42, 20)];
[button setBackgroundImage:[UIImage imageNamed:[imageNameArray objectAtIndex:section]] forState:UIControlStateNormal];
[button setTag:section];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[sectionHeader addSubview:button];
return sectionHeader;
}

3) 如果按下按钮,更改数组中图像的名称

- (void)buttonPressed:(id)sender
{
UIButton *allButton = (UIButton*)sender;

[imageNameArray insertObject:@"selected_image" atIndex:[allButton tag]];
[allButton setBackgroundImage:[UIImage imageNamed:[imageNameArray objectAtIndex:[allButton tag]]] forState:UIControlStateNormal];
}

关于ios - 如何使 uitableview 的部分标题中的按钮保持选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25502098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com