iOS开发——使用代理(Delegate)实现跨界面执行跳转请求

先说说我遇到的问题吧,我自定义了一个UITableViewCell,上面有一个UIButton按钮,我想通过点击这个按钮实现视图跳转,UIButton的点击触发的事件是写在UITableViewCell中的,但视图跳转必须是在UITableViewController中才能实现的。这时候我就想到了通过代理(Delegate)实现这一需求。

先创建一个协议继承NSObject,命名为viewDelegate。
viewDelegate.h中

#import <Foundation/Foundation.h>

@protocol viewDelegate <NSObject>
/*
 *@required标注的方法为必须实现的方法;
 *@optional标注的方法为可以选择实现;
 */
@optional

-(void)setViewControl;//定义setViewControl方法

@end

TableViewCell.h中

#import <UIKit/UIKit.h>
#import "viewDelegate.h"
@interface TableViewCell : UITableViewCell

//委托代理人
@property(nonatomic,weak)id<viewDelegate> Delegate;

@end

TableViewCell.m中

//自定义cell重写init方法
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        //添加所有子控件,这里也就是button
        [self setUpAllChildView];

    }
    return self;
}

-(void)setUpAllChildView
{
    //创建一个UIButton
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(0, 0, 100, 50);
    [button1 setTitle:@"Green" forState:UIControlStateNormal];
    [button1 setTitle:@"BB" forState:UIControlStateSelected];
    [button1 addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button1];   
}

-(void)buttonPressed:(UIButton *)button
{
    //实现按钮不同状态的切换
    button.selected=!button.selected;

    //通知执行协议方法
    [self.Delegate setViewControl];

}

TableViewController.m中

@interface TableViewController ()<viewDelegate>//这个一定要写,而且要记住导入头文件


@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * ID = @"cell";
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if(!cell)
    {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];

        //调用委托方法
        cell.Delegate = self;
    }

    return cell;
}

//实现协议方法
-(void)setViewControl
{
    ViewController *vc = [[ViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

运行代码,效果如下,成功解决了问题。
这里写图片描述这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章