私はしばらくの間、これを理解しようとしています。テーブルビューセル内でプログラムで UIButton を作成しています。ボタンをクリックすると、別のView Controllerにセグエまたはプッシュしたい。StoryBoard を使用し、そこにボタンを作成してから、目的の VC にセグエをコントロールドラッグすると、これは簡単なことです。しかし、私はさまざまな理由でこのようにしたくありません。以下はこれまでの私のコードです。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
// <<<< bunch of code snipped out here to keep this example short >>>
for(UIButton *button in cell.subviews)
{
[button removeFromSuperview];
}
UIImage *image = [UIImage imageNamed:[contentArray_ objectAtIndex:indexPath.row]];
UIButton *imageButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 240, 240)];
[imageButton setImage:image forState:UIControlStateNormal];
imageButton.layer.masksToBounds = YES;
imageButton.layer.cornerRadius = 5.0;
imageButton.layer.borderWidth = 1.0;
imageButton.layer.borderColor = [[UIColor grayColor] CGColor];
CGAffineTransform rotateButton = CGAffineTransformMakeRotation(M_PI_2);
imageButton.transform = rotateButton;
cell.backgroundColor = [UIColor clearColor];
[cell addSubview:imageButton];
return cell;
これで、このテーブルの各行に対して、画像付きのボタンがプログラムで作成されます。ボタンも回転させます - はい、これは水平方向のテーブル ビューです。
では、ボタンのクリックに対してアクションを実行するにはどうすればよいでしょうか。すべてのボタンは同じ宛先ビューコントローラーに移動します...
PS - ARC で Xcode 4.2 を使用しています (本当に重要かどうかはわかりません)。
----- 質問への更新
コードの提案を実装しました(jrturtonに感謝します)が、UITableViewセルにいるため、モーダルビューコントローラーを表示できないと思います。私は今、次のコードを持っています...
.h ファイル:
@interface DetailsHorizontalPhotoCell : UITableViewCell <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) IBOutlet UITableView *horizontalTableView;
@property (nonatomic, strong) NSArray *contentArray;
- (IBAction)photoButton:(id)sender;
@end
.m ファイル:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/// ----- code here to setup the cell, button, image, etc...
// do something when the buttong is pressed
[imageButton addTarget:self action:@selector(photoButton:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (IBAction)photoButton:(id)sender
{
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.horizontalTableView];
NSIndexPath *hitIndex = [self.horizontalTableView indexPathForRowAtPoint:hitPoint];
// do some stuff here to pull object data out of the contentArray
NSLog(@"Image clicked, index: %d", hitIndex.row);
// other non-relevant code snipped to keep this example short
// next I want to present a modal view controller (lets call it PhotoAlbum) which is a TableViewController
PhotoAlbum *photoAlbum = [[PhotoAlbum alloc] init];
// below does not work, does not even autocomplete in Xcode. I believe its because I'm in a UITableViewCell and not a VC... Any suggestions here?
[photoAlbum setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentModalViewController:photoAlbum animated:YES];
}