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];
}

運行代碼,效果如下,成功解決了問題。
這裏寫圖片描述這裏寫圖片描述

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