複数のボタンを持つカスタム UITableViewCell があります。ボタンが選択された状態か選択されていない状態かを記憶し、それをカスタム コア データ モデル クラスのプロパティに保存したいと思います。複数のカスタム UITableViewCells があり、それぞれに異なる数のボタンがあります。
ボタンには、文字列として巧妙に名前が付けられています: 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'
前もって感謝します。私は間違った木を吠えていると思います。
カート