美文网首页iOS学习开发iOS学习
iOS:在单元格中点击按钮,跳转到另一个VC(新手向)

iOS:在单元格中点击按钮,跳转到另一个VC(新手向)

作者: 木鱼_cc | 来源:发表于2016-12-22 20:15 被阅读0次

2017年2月21日更新:重新整理顺序

相信很多朋友在项目过程中,都有遇到过这样一种情况,就是在自定义的一个单元格中,添加一个按钮,按钮的操作是跳转到另一个界面。当我们熟练地打出

 [self.navigationController pushViewController:tempVC animated:YES];

但是这个方法的前提是,这个类必须继承自UIViewController,所以在上面一种情况下,无法调出push或者present方法,那怎么处理呢?有以下三种办法:

第一种方法,寻找当前控制器(最简单的一个)

核心思想是UIResponse这个关系链,给UIView进行扩展

给UIView添加类
#import <UIKit/UIKit.h>

@interface UIView (Extension)
-(UIViewController*)viewController;
@end

#import "UIView+Extension.h"
@implementation UIView (Extension)
-(UIViewController *)viewController{
    
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}
@end

在CustomCell.m文件中实现
[[self viewController]pushViewController:secondVC animated:YES];

第二种(协议方法)

CustomCell.h

#import <UIKit/UIKit.h>
//添加协议
@protocol TempDelegate<NSObject>
-(void)transform;
@end

@interface CustomCell : UITableViewCell
@property(nonatomic,assign)id<TempDelegate> delegate;

CustomCell.m文件中

//在你添加的button控件中添加buttonClick方法
-(void)buttonClick{
    [_delegate transform];
}

UITableViewController.m文件中

//在UITableViewController Data Source设置中
(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Identifier"];
    /*
    cell的一些设置方法
    */
    cell.delegate = self;

}

#pragma mark - TempDelegate
-(void)transform{
    UIViewController *vc = [UIViewController alloc]init];
    [self.navigationController pushViewController:vc animaed:YES];
}

第三种(UITabBarController)

如果我们的项目是利用UITabBarController完成的,我们首先要声明

self.window = [UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];

UITabBarController *mainTabBar = [UITabBarController alloc]init];

self.window.rootViewController = mainTabBar;

[self.window makeKeyAndVisible];

这样做可以把tabBar设置为根控制器,也是大多数项目不走原始Storyboard的方法

接着在我们的自定义单元格CustomCell.m

我们可以寻找他的根控制区,再添加push方法,具体如下

UITabBarController *tabVC = (UITabBarController*)self.window.rootViewControoer;

UINavigationController *naVC = tabVC.selectedViewController;

[naVC pushViewController:targetVC animated:YES];

当然还有许多方法,楼主不是很在行,所以大家可以自行百度。

协议的方法可操作性比较强,也没有那么多限制,同理可用于页面反向传值,我们现在是传方法

但是相比第一种方法操作也相对比较多(我懒).

2016.12.27 感谢评论区一位大神给我带来了最后一个简单又实用的思路@Caiflower

相关文章

网友评论

    本文标题:iOS:在单元格中点击按钮,跳转到另一个VC(新手向)

    本文链接:https://www.haomeiwen.com/subject/tryhvttx.html