简体   繁体   English

Objective-C-需要知道如何向按钮添加另一个目标

[英]Objective-C - Need to know how to add another target to a button

So I have 2 classes(FirstClass and SecondClass). 所以我有2个类(FirstClass和SecondClass)。 FirstClass is a UIViewController, and secondClass is a NSObject class. FirstClass是UIViewController,secondClass是NSObject类。 In the FirstClass i have a button -- dialButton. 在FirstClass中,我有一个按钮-dialButton。

In the SecondClass, I call a method that I made in the FirstClass (changeMethod) 在SecondClass中,我调用在FirstClass中创建的方法(changeMethod)

This Method changes the Method that the button will call when clicked. 此方法更改单击按钮时将调用的方法。 The Method it changes to is a method in the SecondClass (secondClassMethod). 更改为的方法是SecondClass(s​​econdClassMethod)中的方法。

This changeMethod does exactly this: 这个changeMethod正是这样做的:

[dialButton addTarget:secondClass selector:@selector(secondClassMethod)         
forControlEvents:UIControlEventTouchUpInside];

By the way, dialButton is a static button. 顺便说一句,DialButton是一个静态按钮。 What am I doing wrong 我究竟做错了什么

Edit: I fixed the problem above, but now my problem is this: 编辑:我解决了上面的问题,但现在我的问题是:

The button's target method is changed, but the target method isn't called. 按钮的目标方法已更改,但未调用目标方法。

I call the method printPrompt from the SecondClass. 我从SecondClass调用方法printPrompt。

printPrompt: printPrompt:

FirstClass *firstClass =[[FirstClass alloc]init];
[firstClass test];

test: 测试:

SecondClass *secondClass = [[SecondClass alloc]init];
[dialButton removeTarget:self selector:@selector(firstClassMethod) forControlEvent: UIControlEventTouchUpInside];
[dialButton addTarget:secondClass selector:@selector(secondClassMethod)         
forControlEvents:UIControlEventTouchUpInside];

secondClassMethod is not called when i click the button after calling test.. rather, the program crashes. 当我在调用test之后单击按钮时,未调用secondClassMethod。而是,程序崩溃了。

secondClassMethod: FirstClass *firstClass = [[FirstClass alloc]init]; secondClassMethod:FirstClass * firstClass = [[FirstClass alloc] init]; [firstClass setString: @"Test"]; [firstClass setString:@“ Test”];

setString just changes a UIText Field. setString只是更改一个UIText字段。 I've tested it and setString: works. 我已经测试过了,并且setString:有效。


The code you posted will add an additional target/action to the button. 您发布的代码将为按钮添加其他目标/操作。 Buttons can call multiple methods in multiple targets when they are tapped. 轻按按钮可以在多个目标中调用多个方法。

If you want to replace an existing target/action with another one, you have to first remove the existing target/action using the removeTarget:action:forControlEvents: method, then add the new target/action with the code you posted. 如果要用另一个目标/操作替换现有的目标/操作,则必须首先使用removeTarget:action:forControlEvents:方法删除现有的目标/操作,然后使用发布的代码添加新的目标/操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM