【问题标题】:swift: Adding an action to an array of buttonsswift:将动作添加到按钮数组
【发布时间】:2016-05-15 16:00:24
【问题描述】:

我正在设计一个简单的数独应用程序,并且需要在点击 81 个按钮中的任何一个时触发一个动作。我在 ViewController 中创建了一组 UIButton:

class SudokuBoardController : UIViewController {
@IBOutlet var collectionOfButtons: Array<UIButton>?

  override func viewDidLoad() {

    collectionOfButtons.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

    ...
  } 
}

我可以从情节提要中将按钮添加到数组中,好的,就在我尝试 addTarget 时,我收到以下消息:

Value of type 'Array<UIButton>?' has no member addTarget

对于这个问题,是否有不涉及我为每个按钮创建 81 个不同输出的解决方案?

感谢您的帮助!

干杯

【问题讨论】:

    标签: ios uibutton swift2 xcode7 addtarget


    【解决方案1】:

    你有一个Array,所以你想遍历数组中的UIButtons。而且因为您使用的是 Swift,所以您希望以一种 Swifty 的方式进行操作,而不是使用简单的 for 循环。

    collectionOfButtons?.enumerate().forEach({ index, button in
        button.tag = index
        button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
    })
    

    这也很好地处理了collectionOfButtons 是可选的事实,如果它是nil,则什么也不做,而不是崩溃。

    【讨论】:

    • 谢谢!这个答案也有效。多谢。 :)
    【解决方案2】:

    您需要遍历按钮数组并将目标添加到每个按钮。试试下面的代码

    var index = 0
    for button in collectionOfButtons! {
        button.tag = index // setting tag, to identify button tapped in action method
        button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
        index++
    }
    

    【讨论】:

    • 太棒了,这很有效,感谢一位非常感谢 Swift 新手的 Vishnu! :)
    猜你喜欢
    • 2018-11-04
    • 2018-08-10
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2018-02-05
    相关资源
    最近更新 更多