2011-11-18 69 views
2

我正在制作一个ios应用程序,并且无法使用switch语句查看是否按下了UIButton元素。 这就是我想要最终产品工作的人:我有多个无色图像(通过无色我指的是白色,UIImage)。当一个未着色的图像被点击时,子视图会打开彩色框(UIButtons,其中24个,每个都有单独的颜色)。当选择彩色框按钮并按下工具栏上的后退按钮时,子视图关闭并且原始视图重新出现,并且现在用在子视图中选择的所需颜色着色的未着色图像(用于打开子视图的那个图像)重新出现。如何使用switch语句查找UIButton是否被按下?

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

回答

5

我在iOS开发有点生疏,但你也许可以做到以下几点:

设置按钮相同的事件处理程序,并使用发件人属性才能到按钮的标签元素,你可以指定给每个按钮。

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

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

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

+1

你没有生锈,这是我的方式,与标签。我也可以用所有可能的标签'typedef'一个'enum',这更加灵活。 – Cyrille

1

对于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)