gpt4 book ai didi

UITableView 中的 iPhone 动态 UIButton

转载 作者:行者123 更新时间:2023-12-03 21:23:52 26 4
gpt4 key购买 nike

我正在为 UITableView 中的每个单元格行创建一个按钮。该按钮充当将所选行添加为 NSUserDefaults 中“收藏夹”的开关。我的问题是,每当我按下此按钮时,就会在旧按钮之上绘制一个新按钮。我如何正确释放/重用它?这就是我的 cellForRowAtIndexPath 方法的样子:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"cellID";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

}

UIImage *favOn = [UIImage imageNamed:@"favOn.png"];
UIImage *favOff = [UIImage imageNamed:@"favOff.png"];
UIButton *favButton = [[UIButton alloc] initWithFrame:CGRectMake(230, 0, 54, 54)];


favButton.tag = viewTag;

[favButton setImage:favOff forState:UIControlStateNormal];
[favButton setImage:favOn forState:UIControlStateSelected];

if([self getFavState:viewTag]) {

[favButton setSelected:YES];
}
else {
[favButton setSelected:NO];
}

[favButton addTarget:self action:@selector(favButtonSwitch:) forControlEvents:UIControlEventTouchUpInside];
[favButton setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:favButton];
[favButton release];

return cell;
}

此外,我使用三种不同的方法来选择按钮:

- (void) setFavState:(BOOL)state withId:(NSString *)uid {

NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
[savedData setBool:state forKey:uid];
}

- (BOOL) getFavState:(NSString *)uid {

NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];
return [savedData boolForKey:uid];
}

- (void) favButtonSwitch:(id) sender {
NSInteger senderId = [sender tag];
NSString *senderString = [NSString stringWithFormat:@"%i", senderId];

NSLog(@"sender:%i",senderId);

[self getFavState:senderString];

if([self getFavState:senderString]) {

[self setFavState:NO withId:senderString];
}
else {
[self setFavState:YES withId:senderString];
}

[self.tableView reloadData];
}

最佳答案

您似乎每次都会使用新图像创建一个新按钮,即使它是从缓存中检索的。将创建带有图像的按钮的代码移到第一次创建单元格的代码中。

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Move all the image and button creation in here...
}

关于UITableView 中的 iPhone 动态 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259058/

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