【问题标题】:Identify a UIButton that is pressed in swift?识别快速按下的 UIButton?
【发布时间】:2015-10-23 18:12:00
【问题描述】:

如何将 UIButton 元素识别为字符串并在函数调用中使用该字符串?我希望能够知道按下了哪个按钮,然后根据按下的那个按钮提供信息。我会使用字符串插值吗?然后我想使用该字符串并从 Foursquare API 运行查询。

以下是我一直在处理的代码:

首先是按钮名称:

let buttonNames = ["african", "buffet", "burger", "chinese", "fries", "grill", "icecream", "jap", "mex", "pizza", "seafood", "streetfood", "taj", "turkey"

搜索词结果:

var searchTerms = ["African", "All you can eat", "Buffet", "Burgers", "Brazilian", "Breakfast", "BBQ", "Chips", "Chinese", "Cakes", "Café", "Doughnuts", "Dessert", "English Breakfast", "Fast Food", "Fries", "French", "Grill", "Greek", "Italian", "Indian", "Japanese", "Jamaican", "Lebenese", "Mexican", "Pizza", "Street Food", "Sandwhich", "Turkish"]

然后是函数调用:

@IBAction func startSearchQuery() {
    if buttonNames == searchTerms {
        // Do Something
        var parameters = [Parameter.query:""]
        parameters += self.location.parameters()
        let searchTask = session.venues.search(parameters) {
            (result) -> Void in
            if let response = result.response {
                self.venues = response["venues"] as [JSONParameters]?
                self.tableView.reloadData()
            }
        }
        searchTask.start()
    } else {
        print("Search term not found!")
    }
}

如果我能得到一些帮助,我将不胜感激。谢谢大家!

【问题讨论】:

  • 为什么不能使用标签来查找用户被选中的确切按钮?
  • 但是我怎样才能得到标签呢?我会使用字符串插值吗?并将字符串放在这里:'var parameters = [Parameter.query:""]'

标签: ios swift uibutton foursquare


【解决方案1】:

在按钮上放一个标签,你可以通过编程或在属性检查器上做这个,默认标签是0

button.tag = index

@IBAction func startSearchQuery(sender: AnyObject) {

 let button = sender as! UIButton
 let index = button.tag
 let buttonName = buttonNames[index]
  ....
}

【讨论】:

  • 但是我怎样才能得到标签呢?我会使用字符串插值吗?并将标签放在这里:'var parameters = [Parameter.query:""]'
【解决方案2】:

创建两个按钮数组和搜索词。

@IBAction func startSearchQuery(sender: UIButton)
{
    let searchTerm = searchTerms[buttons.indexOf(sender)
    //do your staff
}

或者您可以设置/获取按钮的可访问性标签。

【讨论】:

    【解决方案3】:
      @IBAction func myButton(_ sender: UIButton?) {
                 let button = sender
                 if button?.allControlEvents != .touchUpInside {
                     print("button not pressed from the button")
                 } else {
                     print("button pressed from the button")
                 }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多