Search code examples
iosswiftuitapgesturerecognizer

How do I show a UIPickerView when tapping a UILabel (Swift)?


My app displays the price of something when it boots and I have the list of currencies hidden. When the user taps the price, I want to it reveal the list of currencies hidden below and then hide them again after one is selected. Can't figure out how though, not finding any Swift code for a tap gesture recogniser? I'm you could just do something like priceLabel.isTappedUp = blah blah, years ago, maybe it was Objec C. Any ideas?

Code below:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

let baseURL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC" // API
let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"] // List of currencies
let currencySymbolArray = ["$", "R$", "$", "¥", "€", "£", "$", "Rp", "₪", "₹", "¥", "$", "kr", "$", "zł", "lei", "₽", "kr", "$", "$", "R"]           // Currency symbols
var currencySelected = ""
var finalURL = ""


// Pre-setup IBOutlets
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var currencyPicker: UIPickerView!



override func viewDidLoad() {
    super.viewDidLoad()

    currencyPicker.delegate = self
    currencyPicker.dataSource = self

    currencyPicker.selectRow(5, inComponent:0, animated:false) // Select default currency choice to £

    // Print out the default row price 

    finalURL = baseURL + currencyArray[5]
    print(finalURL)
    currencySelected = currencySymbolArray[5]
    getBitcoinData(url: finalURL)

    currencyPicker.isHidden = true


    priceLabel.isUserInteractionEnabled = true

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}



// Number of columns

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
// Number of rows

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return currencyArray.count // Number of rows = the amount in currency array
}

// Row Title

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
   return currencyArray[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    finalURL = baseURL + currencyArray[row]
    print(finalURL)
    currencySelected = currencySymbolArray[row]
    getBitcoinData(url: finalURL)
}

Solution

  • You can try gesture

        let tapRound = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
    
        priceLabel.isUserInteractionEnabled = true
    
        priceLabel.addGestureRecognizer(tapRound)
    

    //

    @objc func handleTap(_ sender: UITapGestureRecognizer? = nil)
    {
        self.currencyPicker.isHidden = false
    
    }