我正在尝试解决这个问题一段时间。我在 tableview 单元格中以编程方式创建 UIButton。单击按钮后,我想继续或推送到另一个视图控制器。如果我使用 StoryBoard,在此处创建按钮,然后控制并拖动一个 segue 到目标 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];
}