I'm using UIPickerView in button the only problem which I've faced I want user can select the multiple values from UIPickerView not only one values and also change background colour accordingly when user select multiple item.See my code and pic you get an idea what trying to achieve thanks.
#IBOutlet weak var buttonRole: UIButton!
var rolesPicker = UIPickerView()
var toolBar = UIToolbar()
var userRoles:\[String\] = \["Importer","Creater","Writer","Barber"\]
var selectedIndex :Int = 0
#IBAction func didTapPickRoles(_ sender: UIButton) {
rolesPicker = UIPickerView.init()
rolesPicker.delegate = self
rolesPicker.dataSource = self
rolesPicker.backgroundColor = UIColor.white
rolesPicker.autoresizingMask = .flexibleWidth
rolesPicker.contentMode = .center
rolesPicker.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
self.view.addSubview(rolesPicker)
toolBar = UIToolbar.init(frame: CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50))
toolBar.items = \[UIBarButtonItem.init(title: "Done", style: .done, target: self, action: #selector(onDoneButtonTapped))\]
self.view.addSubview(toolBar)
rolesPicker.selectRow(selectedIndex, inComponent: 0, animated: true)
buttonRole.layer.borderWidth = 1
buttonRole.layer.borderColor = UIColor.gray.cgColor
}
#objc func onDoneButtonTapped() {
toolBar.removeFromSuperview()
rolesPicker.removeFromSuperview()
}
}
extension PickerViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return userRoles.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
userRoles\[row\]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedIndex = row
buttonRole.setTitle(userRoles\[row\], for: .normal)
}
}
Related
I created PickerView, but this does not open the PickerView I created. Where do I make a mistake? Why PickerView doesn't open. I added picker view in the text field but it doesn't work. I added it to viewDidLoad, but when I click a text field, picker view does not open.
class EnergyChart: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource {
var picker = UIPickerView()
var gradePickerValues1 : [String] = ["...", ...]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return gradePickerValues1.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return gradePickerValues1[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
getDevice.text = gradePickerValues1[row]
switch row {
case 0: break
default: break
}
self.view.endEditing(true)
}
#objc func cancelTapped() {
self.view.endEditing(true)
}
let getDevice: UITextField = {
let textFieldframe = CGRect()
let textField2 = SkyFloatingLabelTextFieldWithIcon(frame: textFieldframe, iconType: .image)
...
return textField2
}()
#objc func GetDevice() {
self.getDevice.text = self.gradePickerValues1[0]
}
override func viewDidLoad() {
super.viewDidLoad()
picker.backgroundColor = .white
picker.showsSelectionIndicator = true
picker.delegate = self
picker.dataSource = self
getDevice.inputView = picker
GetDevice()
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(..)
toolBar.sizeToFit()
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "İptal", style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancelTapped))
toolBar.setItems([cancelButton, spaceButton], animated: false)
toolBar.isUserInteractionEnabled = true
getDevice.inputAccessoryView = toolBar
view.addSubview(getDevice)
getDevice.snp.makeConstraints { (make) in
make.centerX.equalTo(view).offset(50)
make.top.equalTo(view).offset(510)
make.height.equalTo(50)
make.width.equalTo(200)
}
In my app I have a settings page, and I would like a UIPickerView that works as a check box(lists items and you can enable or disable them). I've looked up different solutions and all I could find was using viewForRow and using UIButton. I am able to add the buttons and it looks good but the buttons don't seem to be tappable.
Heres my implementation:
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView{
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(screenSelectorButtonPress(_:)), for: .touchUpInside)
button.tag = 0
if row == 0{
button.setTitle(Array3[row], for: .normal)
}else{
button.setTitle("\u{2610} \(Array3[row])", for: .normal)
}
return button
}
#objc func screenSelectorButtonPress(_ sender:UIButton!){
print("test")
}
The cells all populate properly but tapping them does nothing.
The functionality that I want is exactly as seen here in safari.
Is there another way to do this or am I doing something wrong with the button? Also yes I could just use switches but our Android version of the app uses a check list like how safari does and we would like to keep it consistent.
You should implement
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int,
inComponent component: Int)
//
self.pickerView.delegate = self
//
class ViewController: UIViewController , UIPickerViewDelegate,UIPickerViewDataSource , UIGestureRecognizerDelegate {
let pickerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
pickerView.frame = CGRect(x: 0, y: 30, width: self.view.frame.width, height: 300)
pickerView.delegate = self
pickerView.dataSource = self
view.addSubview(pickerView)
let tap = UITapGestureRecognizer(target: self, action: #selector(pickerTapped))
tap.delegate = self
pickerView.addGestureRecognizer(tap)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array3.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(row)
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if row == 0 {
return Array3[row]
}
else {
return "\u{2610} \(Array3[row])"
}
}
#objc func pickerTapped(tapRecognizer: UITapGestureRecognizer) {
if tapRecognizer.state == .ended {
let rowHeight = self.pickerView.rowSize(forComponent: 0).height
let selectedRowFrame = self.pickerView.bounds.insetBy(dx: 0, dy: (self.pickerView.frame.height - rowHeight) / 2)
let userTappedOnSelectedRow = selectedRowFrame.contains(tapRecognizer.location(in: self.pickerView))
if userTappedOnSelectedRow {
let selectedRow = self.pickerView.selectedRow(inComponent: 0)
pickerView(self.pickerView, didSelectRow: selectedRow, inComponent: 0)
}
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
recently I need a solution to show a present-like pickerView for choosing data for some property, like profile.
what I did is
1, create a empty project
2, create a AViewController which will be used as subview. And I add a pickerView and a navigation bar into that view and adjust the view's height to around 260.
3, write code in that AViewController's class.
class APickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerView:UIPickerView!
let dataList = [["a","b","c","d"]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//pickerView.dataSource = self
//pickerView.delegate = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return dataList.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataList[component].count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataList[component][row]
}
4, write code in Main ViewController to add the AViewController's View as subview.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let pickerViewController = storyboard?.instantiateViewController(withIdentifier: String(APickerViewController.self)) as! APickerViewController
self.view.addSubview(pickerViewController.view)
self.view.bringSubview(toFront: pickerViewController.view)
pickerViewController.view.frame = CGRect(x: 0, y: self.view.frame.height - 300, width: self.view.frame.width, height: 300)
}
and also one question here actually I'm not that sure the difference.
A:
let pickerViewController = storyboard?.instantiateViewController(withIdentifier: String(APickerViewController.self)) as! APickerViewController
B:
let pickerViewController = APickerViewController()
What's the different of A and B ? If I do some #IBOutlet settings by Interface Builder will be affected or what ?
5, go and ... get weired ...
the function
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataList[component].count
}
sometime's get called many times and sometimes not get called.
and the data was not show in pickerView and sometimes only show row 1,2 and no others and if I flick up or down those 1,2 row data disappeared.
if anyone have a better solution of using pickerView as option popup window ?
Help.
Thanks
class EditViewController: UIViewController,UITextFieldDelegate,UIPickerViewDelegate{
var picker : UIPickerView = UIPickerView()
var toolBar : UIToolbar = UIToolbar()
#IBOutlet var txtFieldState: UITextField!
var stateArray = ["Andaman & Nicobar Island","Andhra Pradesh","Arunachal Pradesh","Assam","Bihar","Chandigarh","Chhattisgarh","Dadra & Nagar"]
override func viewDidLoad() {
super.viewDidLoad()
txtFieldState.delegate = self
}
func textFieldDidBeginEditing(textField: UITextField) {
if textField == txtFieldState{
txtFieldState.inputView = picker
txtFieldState.inputAccessoryView = toolBar
self.configurePicker()
}
}
func configurePicker()
{
picker.alpha = 1.0
picker.backgroundColor = UIColor(red:241/255.0, green:241/255.0, blue:241/255.0, alpha: 1.0)
picker.showsSelectionIndicator = true
picker.delegate = self
picker.selectedRowInComponent(0)
let screenRect = self.view.frame
let pickerSize = picker.sizeThatFits(CGSizeZero)
let x = screenRect.origin.x + (screenRect.size.width / 2) - (pickerSize.width / 2)
let pickerRect = CGRectMake(x,
screenRect.origin.y + (screenRect.size.height) - (pickerSize.height),
pickerSize.width,
pickerSize.height)
picker.frame = pickerRect
let toolbarSize = toolBar.sizeThatFits(CGSizeZero)
toolBar.frame = CGRectMake(x,pickerRect.origin.y, // right under the picker
pickerSize.width, // make them the same width
toolbarSize.height)
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
dropState = row
txtFieldState.text = "\(stateArray[row])"
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return stateArray[row]
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return stateArray.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1
}
}
is it possible to create UIPickerView where there will be text and image in one row?
I know how to create it with text only:
class FirstViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var currArray = ["USD","GBP"]
var flags = ["USD.jpg", "GBP.jpg"]
var picker = UIPickerView()
#IBOutlet weak var currencySelectorLabel: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
picker.delegate = self
picker.dataSource = self
currencySelectorLabel.inputView = picker
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currArray.count
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
currencySelectorLabel.text = currArray[row]
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currArray[row]
}
}
But I would like to have something like this:
Obviously instead of image files' names should be real images.
And I want to assign label text from UIPickerView as it is right now.
With help of this post How can I get images to appear in UI PickerView Component in Swift? everything seems to work!
Try this to implement title and image in PickerView
#IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
picker.delegate = self
picker.dataSource = self
currencySelectorLabel.inputView = picker
}
// MARK: UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currArray[row] as? String
}
// MARK: UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 50, height: 40))
let myImageView = UIImageView(frame: CGRect(x: 60, y: 0, width: 30, height: 30))
let countryLabel = UILabel(frame: CGRect(x: 110, y: 0, width: pickerView.bounds.width - 90, height: 40 ))
myImageView.image = flags[row]
countryLabel.font = UIFont.boldSystemFont(ofSize: 16.0)
countryLabel.textColor = UIColor.white
countryLabel.text = currArray[row] as? String
myView.addSubview(countryLabel)
myView.addSubview(myImageView)
return myView
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// do something with selected row
}
I'm trying to put a done button to my picker view because, when I slide to choose an item the uipickerview automatically select the slided row, so I prefer have a button done:
#IBOutlet var tfProjet: UITextField!
var pvProjetData = ["-Choisir-", "Rachat de crédits", "Renégociation de crédits"]
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
if DeviceType.IS_IPHONE_4_OR_LESS {
pickerView.frame=CGRectMake(0, 200, view.frame.width, 100)
} else if DeviceType.IS_IPHONE_5 {
pickerView.frame=CGRectMake(0, 200, view.frame.width, 200)
} else if DeviceType.IS_IPHONE_6 {
pickerView.frame=CGRectMake(0, 200, view.frame.width, 200)
} else if DeviceType.IS_IPHONE_6P {
pickerView.frame=CGRectMake(0, 200, view.frame.width, 250)
} else if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
pickerView.frame=CGRectMake(0, 200, view.frame.width, 300)
}
// pickerView.backgroundColor = .whiteColor()
pickerView.showsSelectionIndicator = true
pickerView.delegate = self
pickerView.dataSource = self
self.pickerView = pickerView
let pickerToolBar = UIToolbar()
pickerToolBar.barStyle = UIBarStyle.Black //you can change the style
pickerToolBar.translucent = true
pickerToolBar.tintColor = UIColor.whiteColor() // or other colours
pickerToolBar.sizeToFit()
let spaceButtonPicker = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButtonPicker = UIBarButtonItem(title: "Ok", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelDatePicker:")
pickerToolBar.setItems([cancelButtonPicker, spaceButtonPicker], animated: false)
pickerToolBar.userInteractionEnabled = true
tfDateNaissance.inputAccessoryView = pickerToolBar
tfProjet.inputView = pickerView
tfProjet.inputAccessoryView = pickerToolBar
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func selectRow(row: Int, inComponent component: Int, animated: Bool){
}
func updatePicker(){
self.pickerView!.reloadAllComponents()
pickerView.selectRow(0, inComponent: 0, animated: false)
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if tfProjet.isFirstResponder(){
return pvProjetData.count
}
return 1
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if tfProjet.isFirstResponder(){
return pvProjetData[row]
}
return ""
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if tfProjet.isFirstResponder(){
let itemselected = pvProjetData[row]
tfProjet.text = itemselected
self.tfProjet.endEditing(true)
}
}
I see the button Ok, but it doesn't work, when I slide the row is automatically selected.