【问题标题】:Method to track which was the last button pressed of a specific type跟踪哪个是特定类型的最后按下按钮的方法
【发布时间】:2011-12-08 23:09:40
【问题描述】:

我有一个简单的计算器应用程序。我有 4 个操作员按钮和计算器数字。我想跟踪最近按下的操作按钮。

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

我的想法是在 clearDisplay 方法中添加一个 if 语句,例如: 如果(lastOperatorPressed == button1){ 改变它的titleColor…

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

我无法找到一种方法来跟踪最近按下的操作员按钮。

非常感谢任何帮助。

【问题讨论】:

    标签: objective-c ios uibutton uilabel


    【解决方案1】:

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

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

    这里有更多细节:

    如果您使用 Interface Builder,请将每个按钮连接到视图控制器中的按钮处理程序方法。 (我不太会使用 Interface Builder,但我认为您想将 touch-up inside 事件连接到按钮处理程序方法)。

    如果您不使用 Interface Builder,那么您可以在视图控制器中初始化 ivars 的位置添加这一行。假设您的按钮处理程序被称为 buttonHandler: 为您的每个按钮执行此操作:

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

    在您的头文件中,创建一个名为lastButtonPressed 的实例变量(例如)。在初始化其他 ivars 的实现文件中将其初始化为 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;
    
    
    }
    

    【讨论】:

    • 你能详细说明一下这个方法吗?我正在尝试设置它,但没有运气。
    • 非常感谢。我刚刚根据您的第一反应找到了解决方案,我还没有查看您所做的编辑。我在 UIButton *lastOpPressed 和方法 '-(void) lastOperatorPressed (id)sender' 中添加了一个 @property,我只是在其中放置了 lastOpPressed == (UIButton *)sender,并在我的 IBAction 中为操作员添加了 [self lastOperatorPressed nameOfOperatorButton]然后将 if 语句添加到我的 clear 方法中,效果很好!真是太感谢你了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多