Xcode 如何将 UITableView 单元格链接到新的视图控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12428983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:30:01  来源:igfitidea点击:

Xcode how to link UITableView Cells to a new View Controller

iphonexcodexcode4uitableview

提问by Blake Loizides

I currently have developed a Tabbed Based Application. The first Tab is decors which displays Colour Swatches or Images in a TableView Structure. Currently when you push on a image or Colour swatch An alert pops up saying which table cell you have pushed. I instead want to link each table cell image or Colour swatch to a new view controller showing a bigger image of that image or colour swatch. A modal would also do fine

我目前已经开发了一个基于选项卡的应用程序。第一个选项卡是装饰,它在 TableView 结构中显示色板或图像。当前,当您按下图像或颜色样本时,会弹出一个警报,说明您按下了哪个表格单元格。相反,我想将每个表格单元格图像或颜色样本链接到一个新的视图控制器,显示该图像或颜色样本的更大图像。模态也可以

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

#import "TableViewsViewController.h"

@implementation TableViewsViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize table;
@synthesize sitesArray;
@synthesize imagesArray;

#pragma mark -
#pragma mark View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {


// Load up the sitesArray with a dummy array : sites
NSArray *sites = [[NSArray alloc] initWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", nil];
self.sitesArray = sites;
[sites release];

UIImage *active = [UIImage imageNamed:@"a.png"];
UIImage *ae = [UIImage imageNamed:@"b.png"];
UIImage *audio = [UIImage imageNamed:@"c.png"];
UIImage *mobile = [UIImage imageNamed:@"d.png"];
UIImage *net = [UIImage imageNamed:@"e.png"];
UIImage *photo = [UIImage imageNamed:@"f.png"];
UIImage *psd = [UIImage imageNamed:@"g.png"];
UIImage *vector = [UIImage imageNamed:@"h.png"];

NSArray *images = [[NSArray alloc] initWithObjects: active, ae, audio, mobile, net, photo, psd, vector, nil];
self.imagesArray = images;
[images release];

[super viewDidLoad];
}


#pragma mark -
#pragma mark Table View datasource methods

// Required Methods

// Return the number of rows in a section
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [sitesArray count];
}

// Returns cell to render for each row
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure cell

NSUInteger row = [indexPath row];

// Sets the text for the cell
//cell.textLabel.text = [sitesArray objectAtIndex:row];

// Sets the imageview for the cell
cell.imageView.image = [imagesArray objectAtIndex:row];

// Sets the accessory for the cell
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

// Sets the detailtext for the cell (subtitle)
//cell.detailTextLabel.text = [NSString stringWithFormat:@"This is row: %i", row + 1];

return cell;
}

// Optional

// Returns the number of section in a table view
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

#pragma mark -
#pragma mark Table View delegate methods

// Return the height for each cell
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}

// Sets the title for header in the tableview
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Decors";
}

// Sets the title for footer
-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
return @"Decors";
}

// Sets the indentation for rows
-(NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
 {
return 0;
}

// This method is run when the user taps the row in the tableview
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tapped row!" 
                                          message:[NSString stringWithFormat:@"You tapped: %@", [sitesArray objectAtIndex:indexPath.row]]
                                          delegate:nil 
                                          cancelButtonTitle:@"Yes, I did!" 
                                          otherButtonTitles:nil];
[alert show];
[alert release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
NSLog(@"Memory Warning!");
[super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
self.table = nil;
self.sitesArray = nil;
self.imagesArray = nil;
[super viewDidUnload];
}


- (void)dealloc {
[table release];
[sitesArray release];
[imagesArray release];
[super dealloc];
}

@end

Part where the Alert is

警报所在的部分

// This method is run when the user taps the row in the tableview
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tapped row!" 
                                          message:[NSString stringWithFormat:@"You tapped: %@", [sitesArray objectAtIndex:indexPath.row]]
                                          delegate:nil 
                                          cancelButtonTitle:@"Yes, I did!" 
                                          otherButtonTitles:nil];
[alert show];
[alert release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

采纳答案by chown

In didSelectRowAtIndexPathyou can just init another view controller and present. You can present it from self.navigationControllerso that there is a back button if you wish. Here I show it presented modally:

didSelectRowAtIndexPath你可以初始化另一个视图控制器并呈现。self.navigationController如果您愿意,您可以展示它,以便有一个后退按钮。我在这里展示它以模态呈现:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Deselect row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // Declare the view controller
    UIViewController *anotherVC = nil;

    // Determine the row/section on the tapped cell
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0: {
                    // initialize and allocate a specific view controller for section 0 row 0
                    anotherVC = [[ViewControllerForRowZeroSectionZero alloc] init];
                    break;
                }
                case 1: {
                    // initialize and allocate a specific view controller for section 0 row 1
                    anotherVC = [[ViewControllerForRowOneSectionZero alloc] init];
                    break;
                }
            }
            break;
        case 1: {
            // initialize and allocate a specific view controller for section 1 ALL rows
            anotherVC = [[ViewControllerForAllRowsSectionOne alloc] init];
            break;
        }
    }

    // Get cell textLabel string to use in new view controller title
    NSString *cellTitleText = [[[tableView cellForRowAtIndexPath:indexPath] textLabel] text];

    // Get object at the tapped cell index from table data source array to display in title
    id tappedObj = [sitesArray objectAtIndex:indexPath.row];

    // Set title indicating what row/section was tapped
    [anotherVC setTitle:[NSString stringWithFormat:@"You tapped section: %d - row: %d - Cell Text: %@ - Sites: %@", indexPath.section, indexPath.row, cellTitleText, tappedObj]];

    // present it modally (not necessary, but sometimes looks better then pushing it onto the stack - depending on your App)
    [anotherVC setModalPresentationStyle:UIModalPresentationFormSheet];

    // Have the transition do a horizontal flip - my personal fav
    [anotherVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];

    // The method `presentModalViewController:animated:` is depreciated in iOS 6 so use `presentViewController:animated:completion:` instead.
    [self.navigationController presentViewController:anotherVC animated:YES completion:NULL];

    // We are done with the view controller.  It is retained by self.navigationController so we can release it (if not using ARC)
    [anotherVC release], anotherVC = nil;
}

回答by John

Are u using Storyboard? If so, you can build a segue, set it to Modal or Push. Pointing from the TableView to the destination ViewController Then name it with an identifier in the segue's inspector. Then in didSelectRowAtIndexPath, call performSegue: withIdentifier You can also setup the destination ViewController based on the cell selected in prepareForSegue.

你在使用故事板吗?如果是这样,您可以构建一个 segue,将其设置为 Modal 或 Push。从 TableView 指向目标 ViewController 然后在 segue 的检查器中使用标识符命名它。然后在 didSelectRowAtIndexPath 中,调用 performSegue: withIdentifier 也可以根据在 prepareForSegue 中选择的单元格设置目标 ViewController。

Hope it helps.

希望能帮助到你。

回答by matt

You're 90% of the way there! In didSelectRowAtIndexPath, instead of putting up the alert, instantiate and set up the view controller whose view you want to show and call presentViewController:animated:.

你已经完成了 90% 的工作!在 中didSelectRowAtIndexPath,不要设置警报,而是实例化并设置要显示和调用其视图的视图控制器presentViewController:animated:

See my book: http://www.apeth.com/iOSBook/ch19.html#_presented_view_controller

看我的书:http: //www.apeth.com/iOSBook/ch19.html#_presented_view_controller