我有一个带有多个按钮的自定义 UITableViewCell。我想记住按钮是处于选中状态还是未选中状态,并将其存储在自定义核心数据模型类的属性中。有多个自定义 UITableViewCell,每个都有不同数量的按钮。
这些按钮被巧妙地命名为一个字符串:1,2,3...
解释这个项目:想象一位老师想要跟踪学生阅读的章节数以获取书籍列表。目标是跟踪每个学生阅读的章节总数。每本书都是一个 UITableViewCell。每本书都有唯一数量的章节。阅读每一章时,教师(或学生)选择一个按钮。读取的章节将被保存为一个属性,以便下次 UITableViewCell 显示时可以这样显示。
#import "Student.h"
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
chaptersInBook = 16;
self.dickensArray = [NSMutableArray array];
// Book title
UILabel *bookLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 30)];
bookLabel.text = @"David Copperfield";
for (NSInteger index = 0; index < chaptersInBook; index++) // for loop runs 16 times
{
// Need to make correct number of buttons based on the chapters in each book
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag = index;
//buttons in rows of seven
button.frame = CGRectMake(40*(index%7) + 20,40 * (index/7) + 40, 30, 30);
[button setTitle:[NSString stringWithFormat:@"%d", index+1] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",index+1]] forState:UIControlStateNormal];
[button setTitle:[NSString stringWithFormat:@"%d", index+1] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateSelected];
[button addTarget:self action:@selector(toggleOnOff:) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.contentView addSubview:button];
[self.contentView addSubview:bookLabel];
}
}
return self;
}
-(IBAction)toggleOnOff:(id)sender
{
UIButton *button = (UIButton *)sender;
button.selected = !button.selected; // In storyboard the default image and selected image are set
}
-(IBAction)buttonPressed:(id)sender {
UIButton* button = (UIButton *)sender;
if (button.selected) {
int chapter = button.tag + 1;
NSString *nameOfButton = [NSString stringWithFormat:@"%d",chapter];
NSString *buttonIsSelected = @"YES";
//Now I want to set student.ch1 to yes but I want to set the '1' to 'chapter'
//Not sure how to do this: append the name of a property with a variable.
}
所以,我的问题是,如何最好地将按钮状态存储到所选章节的学生属性中?我希望我可以将章节编号附加到“student.ch [在此处附加章节编号]”,但我认为这是不可能的。
//eg.
student.ch1 = [NSNumber numberWithBool:YES];//but replace '1' with the value in the int variable 'chapter'
先感谢您。我想我找错树了。
库尔特