[英]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.