Search code examples
iosiphoneswiftuipickerviewuibarbuttonitem

Swift - Programmatically create and display UIPickerView when BarButtonItem is pressed


Initially I wanted to add a hidden UIPickerView onto the Main.storyboard alongside my existing UISearchBar and when a BarButtonItem is clicked, the UIPickerView should be displayed; but it appears I cannot have them both at once in a given space.

So instead, my best alternative was to create it programmatically. I've followed existing tutorials (http://sourcefreeze.com/ios-uipickerview-example-using-swift/) and similar questions (Programmatically Create and Show UIPickerView) and seems like I do (?) have a UIPickerView as the description of it is being printed and I get the following:

<UIPickerView: 0x7f86425b1fb0; frame = (100 100; 100 162); layer = <CALayer: 0x7f8642543a20>>

Here is part of my current code which may be of help:

AnimalTableViewController.swift

import UIKit

class AnimalTableViewController: UITableViewController, UINavigationControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet var segmentedSortOption: UISegmentedControl!
    var array : NSArray = Animal.animalStruct.jsonResult["animal"] as NSArray
    var filteredArray = [[String:AnyObject]]()
    var timer = NSTimer()
    var counter:Int = 1
    var typePickerView: UIPickerView = UIPickerView()

    @IBOutlet var typeBarButton: UIBarButtonItem!
    var resultSearchController = UISearchController()

    var indexArray:String!

    @IBAction func refresh(sender: AnyObject) {

        self.tableView.reloadData()
        println("refreshed")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.typePickerView.hidden = true
        self.typePickerView.dataSource = self
        self.typePickerView.delegate = self
        self.typePickerView.frame = CGRectMake(100, 100, 100, 162)
        self.typePickerView.backgroundColor = UIColor.blackColor()
        self.typePickerView.layer.borderColor = UIColor.whiteColor().CGColor
        self.typePickerView.layer.borderWidth = 1        
        timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

        self.resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.dimsBackgroundDuringPresentation = false
            controller.searchBar.sizeToFit()

            self.tableView.tableHeaderView = controller.searchBar

            return controller
        })()
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return array.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return array[row]["type1"] as String
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        typeBarButton.title = array[row]["type1"] as? String
        typePickerView.hidden = false
    }

    func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return 36.0
    }

    func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 36.0
    }

    @IBAction func typePickerViewSelected(sender: AnyObject) {
        typePickerView.hidden = false
        println(typePickerView.description)
    }

}

Please could you help me display the programmatically created UIPickerView when the BarButtonItem is pressed? If you have any more questions, please do ask.

Many thanks.


Solution

  • You never add the pickerView as a subview of the ViewController, which you can do in viewDidLoad() since you're hiding it. Then when you unhide it your view should be there.

    EDIT: Added Code

    override func viewDidLoad() {
        super.viewDidLoad()
        self.typePickerView.hidden = true
        //other pickerView code like dataSource and delegate
        self.view.addSubview(pickerView) //will add the subview to the view hierarchy
    }
    

    With the above code, now when you unhide it on button press the view will show up.