gpt4 book ai didi

ios - 协议(protocol)不工作

转载 作者:行者123 更新时间:2023-11-28 21:40:17 25 4
gpt4 key购买 nike

您好,我正在导航栏上以编程方式添加一个自定义按钮,我已经在我的后台类中编写了所有按钮属性,我正在从我的主类中调用此方法

在这里,我使用协议(protocol)从后台类获取主类中的按钮触摸事件,但使用协议(protocol)无法正常工作

我的代码:-

背景类:-

背景类.h

#import <UIKit/UIKit.h>

@protocol buttonprotocol<NSObject>
@required
- (void) buttonTapped;
@end

@interface BackGroundClass : UIViewController

@property (nonatomic, weak) id<buttonprotocol> delegate;

@end

背景类.m

#import "BackGroundClass.h"

@interface BackGroundClass ()

@end

@implementation BackGroundClass
@synthesize delegate;

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

- (void)backbutton: (UINavigationItem *)navigationitem
{
UIImage* image3 = [UIImage imageNamed:@"back.png"];
CGRect frameimg = CGRectMake(15,5,25,25);

UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];

UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
navigationitem.leftBarButtonItem = mailbutton;
}

- (void)Back_btn :(id)sender
{
[delegate buttonTapped];
}

@end

主类:-

主类.h

#import <UIKit/UIKit.h>
#import "BackGroundClass.h"

@interface mainclass : UIViewController<buttonprotocol>

主类.m

#import "mainclass.h"
#import "BackGroundClass.h"

@interface mainclass ()
{
BackGroundClass * bg;
}

@end

@implementation mainclass

- (void)viewDidLoad {
[super viewDidLoad];

bg = [[BackGroundClass alloc]init];
[bg backbutton:self.navigationItem];
}

- (void)buttonTapped
{
NSLog(@"ok it's 2");
}

但是上面那个点击按钮的方法没有调用我做错了什么?

最佳答案

当您创建 BackGroundClass 类的对象时,您没有将类的委托(delegate)设置为 self,这就是为什么您的委托(delegate)方法没有调用,像这样尝试

bg = [[BackGroundClass alloc]init];
bg.delegate = self;

关于ios - 协议(protocol)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442649/

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