Identify a UIButton that is pressed in swift?
19,869
Solution 1
Put a tag on the button, you can do this programmatically or on the attribute inspector, the default tag is 0
button.tag = index
@IBAction func startSearchQuery(sender: AnyObject) {
let button = sender as! UIButton
let index = button.tag
let buttonName = buttonNames[index]
....
}
Solution 2
Create two arrays of buttons and search terms.
@IBAction func startSearchQuery(sender: UIButton)
{
let searchTerm = searchTerms[buttons.indexOf(sender)
//do your staff
}
Or you can set/get accessibility labels for buttons.
Author by
user5481206
Updated on June 04, 2022Comments
-
user5481206 almost 2 years
How can I identify a UIButton element as a string and use that string in a function call? I want to be able to know what button has been pressed and then provide information based on that button that has been pressed. Would I use String Interpolation? I then want to use the string and run a query from the Foursquare API.
Below is the code I have been working on:
Firstly the button names:
let buttonNames = ["african", "buffet", "burger", "chinese", "fries", "grill", "icecream", "jap", "mex", "pizza", "seafood", "streetfood", "taj", "turkey"
The search term results:
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"]
Then the function call :
@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!") } }
If I can get some help on this I will be grateful. Thanks all!
-
good4pc over 8 yearswhy cant you use a tag for finding the exact button which the user has been selected ?
-
Caleb over 8 yearsPossible duplicate of Swift - determine which button was pressed with switch
-
user5481206 over 8 yearsBut how would I get get the tag though? Would I use String Interpolation? And put the string in here: 'var parameters = [Parameter.query:""]'
-
-
user5481206 over 8 yearsBut how would I get get the tag though? Would I use String Interpolation? And put the tag in here: 'var parameters = [Parameter.query:""]'