gpt4 book ai didi

ios - UIViewController方法旋转不起作用

转载 作者:行者123 更新时间:2023-12-01 18:42:03 25 4
gpt4 key购买 nike

我在UIViewController上使用类别来在多个ViewController上混淆viewWillAppear:方法。

@implementation UIViewController (Tracking)

+(void)load
{
static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
Class class = [self class];

SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xx_viewWillAppear:);

Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));

if (didAddMethod)
{
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}

});
}

-(void)xx_viewWillAppear:(BOOL)animated
{
[self xx_viewWillAppear:animated];

NSLog(@"VC loaded");
}

@end

当我从Storyboard加载初始VC时,永远不会调用swizzled方法。仅当VC中的viewWillAppear方法被注释掉时才调用它。但是,当我删除类别并将代码移到单独的VC中时,两种方法都将被调用。
#import "ViewController.h"
#import "UIViewController+Tracking.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"Inside Controller1");
}

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

@end

是否可以在VC中实现viewWillAppear吗?如果没有,如果需要在VC的viewWillAppear中编写一些代码,该如何处理?

最佳答案

您需要从super中调用viewWillAppear:中的ViewController,否则基类(UIViewController)中的方法将不会执行,这就是您所困扰的方法。

以下版本的viewWillAppear:应该会给您预期的结果:

-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"Inside Controller1");
}

关于ios - UIViewController方法旋转不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41473342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com