我有一个联系人列表,他们的名字旁边有一个复选框。
1 http://i.minus.com/jyLvkUt7wnxYs.png
我想在选中单元格文本时将其存储到数组中,当未选中时将其从数组中删除。我的代码只有在选择 1 时才能正常工作,但是当我选择多个复选框时,当我记录它时,它只给我 1 个值。下面是我的代码。
#import <UIKit/UIKit.h>
#import "AddressBookViewController.h"
@class AddressBookViewController;
@interface AddressBookCell : UITableViewCell {
IBOutlet UIButton *checkbox;
NSMutableArray *array;
}
@property (nonatomic, retain) IBOutlet UIButton *checkbox;
@end
.m 文件
#import "AddressBookCell.h"
@implementation AddressBookCell
@synthesize checkbox;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect checkboxRect = CGRectMake(135, 150, 36, 36);
[self.checkbox setFrame:checkboxRect];
[self.checkbox setImage:[UIImage imageNamed:@"unselected@2x.png"]forState:UIControlStateNormal];
[self.checkbox setImage:[UIImage imageNamed:@"selected@2x.png"] forState:UIControlStateSelected];
[self.checkbox addTarget:self action:@selector(checkboxClicked:) forControlEvents:UIControlEventTouchUpInside];
self.accessoryView = self.checkbox;
array = [[NSMutableArray alloc]init];
}
return self;
}
-(void)checkboxClicked:(UIButton *)sender{
sender.selected = !sender.selected;
UITableViewCell *cell = (UITableViewCell *)sender.superview;
if(sender.selected){
[array addObject:cell.textLabel.text];
}else{
if([array containsObject:cell.textLabel.text]){
[array removeObject:cell.textLabel.text];
NSLog(@"it got removed");
}
}
NSLog(@"%@",array);
}
-(void)dealloc{
[super dealloc];
}
编辑
-(void)checkboxClicked:(UIButton *)sender{
sender.selected = !sender.selected;
UITableViewCell *cell = (AddressBookCell *)sender.superview;
if(sender.selected){
[abController.savedPeople addObject:cell.textLabel.text];
}else{
if([abController.savedPeople containsObject:cell]){
[abController.savedPeople removeObject:cell];
}
}
}