Delegado de iOS

1. Descripción

1. Uso de agentes

Generalmente se utiliza para lógica e interacción con la interfaz de usuario. Ejemplo: se agregan lógicamente 50 monedas de oro. En este momento, es necesario actualizar la visualización de monedas de oro en la interfaz de usuario. O necesita llamar a otra UIView. Este ejemplo se utiliza para llamar a AlertView después de 5 segundos.

Cree un archivo de clase llamado DelegateDemo que herede de NSObject

2. Implementación del código

DelegateDemo.h
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import <Foundation/Foundation.h>

//协议定义
//定义一个代理协议 DelegateDemoProtocol 及代理方法 showDelegateAlertView
@protocol DelegateDemoProtocol <NSObject>

-(void)showDelegateAlertView;//此代理方法为 实现具体功能的方法

@end

NS_ASSUME_NONNULL_BEGIN

@interface DelegateDemo : NSObject

//遵循协议的一个代理变量定义
@property(nonatomic,weak) id<DelegateDemoProtocol> delegateDemoProtocol;

-(void)startTimer;//暴露给外部调用

@end

NS_ASSUME_NONNULL_END

DelegateDemo.m
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import "DelegateDemo.h"

@implementation DelegateDemo

//5秒后更新UI(或金币增加更新UI面板显示)
-(void)startTimer{
    
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerProtocol) userInfo:nil repeats:NO];
}

-(void)timerProtocol{
    
    [self.delegateDemoProtocol showDelegateAlertView];//使用代理更新UI界面
}

@end

ViewController.m
//
//  ViewController.m
//  iOS 代理
//
//  Created by MangoChips on 2020/10/25.
//  Copyright © 2020 MangoChips. All rights reserved.
//

#import "ViewController.h"

#import "DelegateDemo.h"

@interface ViewController ()<DelegateDemoProtocol>//需先遵循协议

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    DelegateDemo *delegateDemo = [[DelegateDemo alloc] init];
   delegateDemo.delegateDemoProtocol = self;
   [delegateDemo startTimer];
}

//"被代理对象"实现协议声明的方法,由"代理对象"调用
-(void)showDelegateAlertView{
    NSLog(@"5S After");
    
    //UIAlertView已经被遗弃使用,真机可以运行,模拟器会崩溃。log正常输出
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"5s 时间到" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];

    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
    
}
@end

dirección git

Supongo que te gusta

Origin blog.csdn.net/X_King_Q/article/details/109242865
Recomendado
Clasificación