CollectionViewControllerとCollectionViewCellがあります。データベースからデータをフェッチしているので、コントローラーがロードされると、対応するセルが動的に作成されます。
すべてのセルにはUIButtonとUITextViewがあります。UIButtonを使用して、画像を表示したり(データベースに存在する場合)、画像をキャプチャしたりしています(押されている場合)。
InboundCollectionViewController.m
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
InboundCollectionViewCell *inboundDetailCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"InboundDetailCell" forIndexPath:indexPath];
Image *current = [images objectAtIndex:indexPath.row];
[inboundDetailCell.imageType setText:[NSString stringWithFormat:@"%@", [current pd_description]]];
if ([current.pd_image isKindOfClass:[NSData class]] == NO) {
[inboundDetailCell.imageButton addTarget:self action:@selector(useCamera) forControlEvents:UIControlEventTouchUpInside];
}
else {
[inboundDetailCell.imageButton setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
}
return inboundDetailCell;
}
ここまでは順調ですね。アプリを起動します。コレクションビューコントローラは、データベースからの結果に応じて、セルを自動的に入力します。
画像フィールドに画像がある場合は、カスタムimageButtonのimageプロパティに「check.png」が読み込まれます。
画像フィールドに画像がない場合、imageButtonのTouchUpInsideアクションはメソッド'useCamera'に設定されます。
- (void)useCamera
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
}
else
{
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
[imagePicker setDelegate:self];
[self presentViewController:imagePicker animated:YES completion:NULL];
}
今、私がフォローしているチュートリアルによると、次のコードを実装する必要があります。
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// set image property of imageButton equal to the value in UIImage 'image' variable ???
[self dismissViewControllerAnimated:YES completion:NULL];
}
私が見つけたほとんどの例では、ImageViewとImagePickerControllerは同じViewController内に作成されています。したがって、ImageView(または私の場合はボタン)のimageプロパティに簡単にアクセスできます。
私の問題は、「IBOutlet UIButton imageButton」が、InboundCollectionViewControllerではなくInboundCollectionViewCell内にあることです。そのため、カメラから返された画像をボタンのimageプロパティに渡す方法が見つかりません。
私はObjectiveCとXcodeの両方に非常に慣れていないことに注意してください。これは、私の最初のプロジェクトです。:P :)
前もって感謝します!