![](/img/trans.png)
[英]iphone UITextField changes in a UITableView with a UIButton
[英]iPhone dynamic UIButton in UITableView
我正在为UITableView
每个单元格行创建一个按钮。 该按钮用作在NSUserDefaults
所选行添加为“收藏夹”的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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.