如何使用switch语句来查找UIButton是否被按下?

3
我正在制作一个iOS应用程序,但在使用switch语句检测UIButton元素是否被按下时遇到了问题。
这是我希望最终产品的工作方式:我有多个未着色的图像(白色UIImage),当点击未着色的图像时,打开一个子视图,其中包含彩色方块(24个UIButtons,每个都有不同的颜色)。当选择了一个彩色方块按钮并按下工具栏上的返回按钮后,子视图关闭,原始视图重新出现,并将未染色的图像(打开子视图所选的那个图像)以所选的颜色染色。
我想使用switch语句找到哪个未着色的图像和哪个颜色被选中(所有的UIButton元素)。由于涉及到UIButtons,我不知道在switch语句中该写什么表达式。switch语句的其余部分比较UIButton元素的值,以确定它是否等于YES(当按钮被按下时),如果是,则返回一个字符串。我还想知道如何将IBAction连接到UIImage(这样当图像被点击时就会打开一个子视图)。
2个回答

6

我对iOS开发有点生疏,但您可以按照以下步骤进行:

将按钮设置为相同的事件处理程序,并使用发送器属性来访问按钮的标记元素,您可以为每个按钮指定它。

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

如果这不适合您,您可以使用任何您认为合适的按钮属性来区分它们,如标题、标题颜色等。
对于最佳实践,我建议在尝试将其转换为对象之前,先检查发送方是否为UIButton类型。

1
你并不生疏,这正是我会用标签的方式。我还会使用typedef来定义一个包含所有可能标签的枚举类型,这样更加灵活。 - Cyrille

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接