objective-c - 跟踪最后按下特定类型按钮的方法

标签 objective-c ios uibutton uilabel

我有一个简单的计算器应用程序。我有 4 个运算符(operator)按钮和计算器数字。我想跟踪最近按下的是哪个运算符(operator)按钮。

当按下任何操作按钮时,其标签的颜色会从白色变为橙色。然后当按下数字按钮时,标签恢复为白色。我想要做的是,如果用户在按下另一个运算符或等号之前按下清除键,则标签会变回橙色。

我的想法是在 clearDisplay 方法中有一个 if 语句,例如: 如果(lastOperatorPressed == button1){ 改变它的标题颜色…

因此,如果用户输入一系列数字然后点击 +,+ 按钮将被注册为最近按下的运算符按钮,然后如果他们继续输入下一系列数字并在按下另一个运算符或等于之前按下清除,我在 clearDisplay 中的 if 语句将被触发。

我无法找到一种方法来跟踪最近按下的运算符(operator)按钮。

非常感谢任何帮助。

最佳答案

您可以通过相同的方法处理所有按钮按下操作,其中 (id)sender 是传递的参数值。然后,您可以通过将 (UIButton*)sender 的值与特定按钮对象值进行比较(通过强制转换)来进行特定于按钮的处理。在这个单一方法中,现在您始终拥有 sender 的值,即最后按下的按钮。将其分配给一个变量,例如 lastButtonPressed = sender;

更新:抱歉,应该像 lastButtonPressed = (UIButton*)sender;

这里有更多的细节:

如果您使用 Interface Builder,请将每个按钮连接到 View Controller 中的按钮处理程序方法。 (我不太使用 Interface Builder,但我认为您想将内部事件中的 touch-up 连接到按钮处理程序方法)。

如果您不使用 Interface Builder,那么您可以在 View Controller 中初始化 ivar 的地方添加这一行。假设您的按钮处理程序称为 buttonHandler: 对您的每个按钮执行此操作:

[oneOfYourButtons addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventTouchUpInside];
//... include this for each button ...
[anotherOneOfYourButtons addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventTouchUpInside];

在您的头文件中,创建一个名为 lastButtonPressed 的实例变量(例如)。在您初始化其他 ivar 的实现文件中将其初始化为 nil。

然后添加这样的方法:

- (void)buttonHandler:(UIButton*)sender{

    if (sender == button1) {
       //... do things for button1
       // what you do here may depend on the value of lastButtonPressed, like this, for example
        if (lastButtonPressed == someButton) {
           //... do something 
           //... you may want to reset the value of lastButtonPressed
           lastButtonPressed = nil; 

    }
    else if (sender == button2) {
       //... do things for button2
    }
    else if (sender == button3) {
       //... do things for button3
    }
    else
       //... Repeat for all the buttons you want to handle. The compiler will optimize this so don't worry about that
       //...

    // probably at the end, you want to save the current button as the last button pressed
    lastButtonPressed = sender;


}

关于objective-c - 跟踪最后按下特定类型按钮的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8439040/

相关文章:

objective-c - iOS - UIView 边框底部宽度?

ios - 覆盖 Spritekit 中的触摸

ios - 在 Objective-C 中,如何以编程方式获取设备的 BuildID

IOS Swift assetForURL 错误

ios - 添加 firebase 崩溃分析脚本后获取 Shell 脚本调用警告

ios - 是否可以在WEBUI 的链接中拦截点击处理程序,并添加自定义点击操作?

ios - 在 iOS 6 中保留应用程序

ios - swift 2 : checking the timeinterval repeatedly in iOS

ios - 在 Swift 中找不到 Double 类型的初始值设定项

iphone - IBAction 或 [UIButton addTarget :action: forControlEvents:] for UIButton created in . xib 文件?哪种方法更好?