iOS--代理

本文介绍了一个使用Delegate模式的iOS应用实例。通过ViewController、SecondController及TestView组件展示如何利用Delegate模式实现视图间的跳转。ViewController引入TestView,并遵循TestView定义的LuckyCoderCaiDelegate协议,点击TestView中的按钮即可触发跳转至SecondController。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述: 两个控制器(ViewController和SecondController)和一个view(TestView);控制器带导航;TestView视图引入到ViewController中,TestView中声明一个代理协议,方法是点击在view中的一个button可以push到SecondController,让ViewController遵守协议。

结构:

代码:

##- AppDelegate

//
//  AppDelegate.m
//  luckyCoderCai_delegateTest
//
//  Created by luckyCoderCai on 16/9/7.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor orangeColor];
    
    ViewController *vc = [[ViewController alloc] init];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
    self.window.rootViewController = nav;
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

复制代码

##- ViewController

//
//  ViewController.m
//  luckyCoderCai_delegateTest
//
//  Created by luckyCoderCai on 16/9/7.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import "ViewController.h"
#import "TestView.h"
#import "SecondController.h"

@interface ViewController ()<LuckyCoderCaiDelegate>//遵守代理协议

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.title = @"ViewController";
    
    self.view.backgroundColor = [UIColor cyanColor];
    
    [self createUI];
    
}

/**
 *  UI
 */
- (void)createUI
{
    TestView *testView = [[TestView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    //设置代理对象
    testView.delegate = self;
    [self.view addSubview:testView];
}

#pragma mark -代理
- (void)pushNextController
{
    //代理对象执行方法
    SecondController *secondVC = [[SecondController alloc] init];
    [self.navigationController pushViewController:secondVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

复制代码

##- SecondController

//
//  SecondController.m
//  luckyCoderCai_delegateTest
//
//  Created by luckyCoderCai on 16/9/7.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import "SecondController.h"

@interface SecondController ()

@end

@implementation SecondController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"SecondVC";
    self.view.backgroundColor = [UIColor purpleColor];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

复制代码

##- TestView

##.h:

//
//  TestView.h
//  luckyCoderCai_delegateTest
//
//  Created by luckyCoderCai on 16/9/7.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  代理协议名称
 */
@protocol LuckyCoderCaiDelegate <NSObject>

//方法 可选
@optional
- (void)pushNextController;

@end

@interface TestView : UIView

//声明代理属性
@property (nonatomic, weak) id<LuckyCoderCaiDelegate>delegate;

@end

复制代码

##.m:

//
//  TestView.m
//  luckyCoderCai_delegateTest
//
//  Created by luckyCoderCai on 16/9/7.
//  Copyright © 2016年 luckyCoderCai. All rights reserved.
//

#import "TestView.h"

@implementation TestView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initViews];
    }
    return self;
}

- (void)initViews
{
    self.backgroundColor = [UIColor yellowColor];
    UIButton *pushBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    pushBtn.backgroundColor = [UIColor blueColor];
    pushBtn.frame = CGRectMake(100, 100, 80, 30);
    [pushBtn setTitle:@"push" forState:UIControlStateNormal];
    [pushBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    pushBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [pushBtn addTarget:self action:@selector(pushBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:pushBtn];
    
}

#pragma mark -
- (void)pushBtnAction
{
    //安全判断
    if (self.delegate && [self.delegate respondsToSelector:@selector(pushNextController)]) {
        //代理执行
        [self.delegate pushNextController];
    }
}

@end

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值