【问题标题】:How do I use a switch statement to find if a UIButton is pressed?如何使用 switch 语句来查找 UIButton 是否被按下?
【发布时间】:2011-11-18 20:24:42
【问题描述】:

我正在制作一个 ios 应用程序,但在使用 switch 语句查看是否按下了 UIButton 元素时遇到了问题。 这就是我希望最终产品工作的人:我有多个未着色的图像(未着色的意思是白色,一个 UIImage)。当点击未着色的图像时,会打开一个带有彩色框的子视图(UIButtons,其中 24 个,每个都有单独的颜色。)。当一个彩色框按钮被选中并按下工具栏上的后退按钮时,子视图关闭,原始视图重新出现,未着色的图像(选择打开子视图的图像)现在用子视图中选择的所需颜色着色.

我想使用 switch 语句来查找选择了哪个未着色的图像和哪个颜色(所有 UIButton 元素)。我不知道在 switch 语句中应该放什么作为表达式,因为我正在处理 UIButtons。 switch 语句的其余部分比较 UIButton 元素的值,看它是否等于 YES(按下按钮时),如果是,则返回一个字符串。我还想知道如何将 IBAction 连接到 UIImage(因此当点击图像时会打开子视图)。

【问题讨论】:

    标签: ios nsstring uibutton uiimage switch-statement


    【解决方案1】:

    我对 iOS 开发有点生疏,但您可能可以执行以下操作:

    将按钮设置为相同的事件处理程序,并使用 sender 属性获取您可以为每个按钮指定的按钮的标记元素。

    - (IBAction) doStuff:(id) sender {
    UIButton *button = (UIButton*) sender;
    switch(button.tag)
    {
       //do stuff
    }
    

    如果这不适合您,您可以使用任何您认为合适的按钮属性来区分它们,例如标题、标题颜色等。

    为了获得最佳实践,我建议您在尝试将其转换为对象之前检查发件人是否为 UIButton 类型。

    【讨论】:

    • 你并不生疏,这正是我的做法,带有标签。我还会 typedefenum 加上所有可能的标签,这样更灵活。
    【解决方案2】:

    对于Swift 3.0,我们不再需要观察标签了。只需保留对您的按钮(IBOutlet 或一些私有变量)的引用,然后使用Identifier Pattern 打开按钮本身。

    import UIKit
    
    class Foo {
        // Create three UIButton instances - can be IBOutlet too
        let buttonOne = UIButton()
        let buttonTwo = UIButton()
        let buttonThree = UIButton()
    
        init() {
            // Assign the same selector to all of the buttons - Same as setting the same IBAction for the same buttons
            [buttonOne, buttonTwo, buttonThree].forEach{(
                $0.addTarget(self, action: Selector(("buttonTapped")), for: .touchUpInside)    
            )}
        }
    
        func buttonTapped(sender: UIButton) {
            // Lets just use the Identifier Pattern for finding the right tapped button
            switch sender {
            case buttonOne:
                print("button one was tapped")
            case buttonTwo:
                print("button two was tapped")
            case buttonThree:
                print("button three was tapped")
            default:
                print("unkown button was tapped")
                break;
            }
        }
    }
    
    // Example
    let foo = Foo()
    foo.buttonTapped(sender: foo.buttonOne)
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多