Quantcast
Channel: Active questions tagged uipickerview - Stack Overflow
Viewing all 592 articles
Browse latest View live

How to create single Done and Cancel button for all the PickerViews?

$
0
0

I'm trying to achieve is that Done button should save the particular picker view row value to that specific UITextField.I've two pickerview inside a single view controller.

override func viewDidLoad() {     textField1.inputView = pickerview1     textField2.inputView = pickerview2     let toolBar = UIToolbar()     toolBar.barStyle = UIBarStyle.default     toolBar.isTranslucent = true     toolBar.sizeToFit()     let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: #selector(self.cancelPicker))     let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)     let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.donePicker))     toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)     toolBar.isUserInteractionEnabled = true     textField1.inputAccessoryView = toolBar     textField2.inputAccessoryView = toolBar       }  @objc func cancelPicker() {     //cancel that particular pickerview   }    @objc func donePicker() {      // get that particular value in textfield    }

both the textfields and pickerviews are connected as IBOutlets.


How to change the UIPickerView text color?

$
0
0

The default UIPickerView color for text is black. There has been some updates to the language in Swift4. I have found my own solution and answered below.

Pickerview with UITextField

$
0
0

I am making an app that has an excel sheet of data. I would like to insert that excel sheet into a picker view that is connected to a textfield. I then would like the user to input into the textfield where it will show the picker view, and then filter it to which ever the user is typing in. Can anyone point me in the right direction with this? I am coding in swift and using storyboards.

Thanks!

How to make a UIDatePicker appear at bottom of screen?

$
0
0

I currently use MonoTouch with MonoTouch.Dialog. When tapping on a date field it pushes the navigationcontroller so you go right a screen to see your UIDatePicker where you choose the date then go "back" to the main screen again. I'd really like to have this UI like other apps I've used that when you select a date field the UIDatePicker appears at the bottom of the current screen.

I would like to learn how to do this and apply it to other input fields where I may want to use a custom picker that also presents itself at the bottom of the current screen.

Does anyone have any code to share that would allow a UIPicker/UIDatePicker to appear at the bottom of the active screen?

Thank you.

Multi-Component Picker (UIPickerView) in SwiftUI

$
0
0

I'm trying to add a three-component Picker (UIPickerView) to a SwiftUI app (in a traditional UIKit app, the data source would return 3 from the numberOfComponents method), but I can't find an example of this anywhere.

I've tried adding an HStack of three single-component Pickers, but the perspective is off from what it would be if they were all part of a single Picker.

UIPickerView String + Image

$
0
0

I would like to ask help for combining String and Image in UIPickerView, I'm having a hard time figuring out the ViewForRow

ViewModel.swift

import UIKit

class ViewModel: NSObject {

var item1 = ["item1A", "item1B", "item1C"]var item2 = ["item2A", "item2B", "item2C"]

ViewController.swift

func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{    if pickerView.tag == 0 {        return self.viewModel.item1.count    } else if pickerView.tag == 1 {        return self.viewModel.item2.count    }func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if pickerView.tag == 0 {        return self.viewModel.item1[row]    } else if pickerView.tag == 1 {        return self.viewModel.item2[row]    }func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    if pickerView.tag == 0 {        rslt1.text = self.viewModel.item1[row]        rslt1.resignFirstResponder()    } else if pickerView.tag == 1 {        currentSizeSelection = row        rslt2.text = self.viewModel.item2[row]        rslt2.resignFirstResponder()    }

UIPickerView delegate inside of TableViewCell not called

$
0
0

I have a TableViewCell that contains a UIPickerView. The problem is, that the delegate of UIPickerView is not getting called

extension ViewController: UITableViewDelegate, UITableViewDataSource {    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return 3    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let cell = tableView.dequeueReusableCell(withIdentifier: "testCell") as! TableViewCell        cell.setupCell(indexPath: indexPath.row)        return UITableViewCell()    }}class TableViewCell: UITableViewCell {    public var picker = UIPickerView()    private var index = 1    override func awakeFromNib() {        super.awakeFromNib()        // Initialization code        print("awakeFromNib")        picker.dataSource = self        picker.delegate = self            }    public func setupCell(indexPath: Int) {        print("setupcell")        index = indexPath        contentView.addSubview(picker)        picker.translatesAutoresizingMaskIntoConstraints = false        picker.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor).isActive = true        picker.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor).isActive = true        picker.topAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true    }}extension TableViewCell: UIPickerViewDataSource, UIPickerViewDelegate {    func numberOfComponents(in pickerView: UIPickerView) -> Int {                return 3    }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return 10    }    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        return "abc"    }}

I tried to reload picker using picker.reloadAllComponents(), but then only func numberOfComponents(in pickerView: UIPickerView) is getting called. What am i missing? The problem is for sure with my cell.

How to disable UIPickerView (Objective-C)?

$
0
0

Is there a way to make the UIPickerView read-only? This means that the user cannot flip through the options.

PS. This is not the same as not passing anything in the didSelectRow method because I only want the user to see that the picker is there and not to touch it.


How to disable UIPickerView (Swift)?

$
0
0

I would like to disable the UIPickerView, but setting it to "isEnabled = false" does not work. And no, I don't want to disable the view while using it, but instead not being able to scroll through the view until a certain action is done for it to be re-enabled.

The code I tried here doesn't work (it may not even be swift code): How to disable UIPickerView (Objective-C)?

SwiftUI - Styling Picker

$
0
0

I have a Picker like this:

enter image description here

Im trying to change the style so it pops up like the keyboard does, see example:

enter image description here

This is my code at the moment:

Picker(selection: $profileViewModel.age, label: Text("Age")) {     ForEach(0 ..< 100) { number in          Text("\(number)")     }}.pickerStyle(WheelPickerStyle())

How do I change the font size in a UIPickerView in Swift?

$
0
0

How do I change the font size in a picker view? I have read a lot of questions about this, but none are in Swift 3. I have three picker views; the first two have two columns and have the same data source and delegate. The last one has one column and has a different data source and delegate. I can't fit the text in the first two picker views by one character. How do I shrink the font size in a UIPickerView and adjust the picker view row height, if necessary? Thanks.

class ViewController: UIViewController {//MARK: Properties@IBOutlet weak var layoutLengthPicker: UIPickerView!@IBOutlet weak var layoutWidthPicker: UIPickerView!@IBOutlet weak var trackPicker: UIPickerView!let layoutLengthPickerDelegate = DimensionsPickerDelegate()let layoutWidthPickerDelegate = DimensionsPickerDelegate()let trackPickerDelegate = TrackPickerDelegate()override func viewDidLoad() {    super.viewDidLoad()    layoutLengthPicker.delegate = layoutLengthPickerDelegate    layoutLengthPicker.dataSource = layoutLengthPickerDelegate    layoutWidthPicker.delegate = layoutWidthPickerDelegate    layoutWidthPicker.dataSource = layoutWidthPickerDelegate    trackPicker.delegate = trackPickerDelegate    trackPicker.dataSource = trackPickerDelegate    // Do any additional setup after loading the view, typically from a nib.}//MARK: Actionsoverride func didReceiveMemoryWarning() {    super.didReceiveMemoryWarning()    // Dispose of any resources that can be recreated.    }}class DimensionsPickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {let feet = ["0 Ft.", "1 Ft.", "2 Ft.", "3 Ft.", "4 Ft.", "5 Ft.", "6 Ft.", "7 Ft.", "8 Ft.", "9 Ft.", "10 Ft.", "11 Ft.", "12 Ft.", "13 Ft.", "14 Ft.", "15 Ft.", "16 Ft.", "17 Ft.", "18 Ft.", "19 Ft.", "20 Ft.", "21 Ft.", "22 Ft.", "23 Ft.", "24 Ft.", "25 Ft.", "26 Ft.", "27 Ft.", "28 Ft.", "29 Ft.", "30 Ft.", "31 Ft.", "32 Ft.", "33 Ft.", "34 Ft.", "35 Ft.", "36 Ft.", "37 Ft.", "38 Ft.", "39 Ft.", "40 Ft.", "41 Ft.", "42 Ft.", "43 Ft.", "44 Ft.", "45 Ft.", "46 Ft.", "47 Ft.", "48 Ft.", "49 Ft.", "50 Ft.", "51 Ft.", "52 Ft.", "53 Ft.", "54 Ft.", "55 Ft.", "56 Ft.", "57 Ft.", "58 Ft.", "59 Ft.", "60 Ft.", "61 Ft.", "62 Ft.", "63 Ft.", "64 Ft.", "65 Ft.", "66 Ft.", "67 Ft.", "68 Ft.", "69 Ft.", "70 Ft.", "71 Ft.", "72 Ft.", "73 Ft.", "74 Ft.", "75 Ft.", "76 Ft.", "77 Ft.", "78 Ft.", "79 Ft.", "80 Ft.", "81 Ft.", "82 Ft.", "83 Ft.", "84 Ft.", "85 Ft.", "86 Ft.", "87 Ft.", "88 Ft.", "89 Ft.", "90 Ft.", "91 Ft.", "92 Ft.", "93 Ft.", "94 Ft.", "95 Ft.", "96 Ft.", "97 Ft.", "98 Ft.", "99 Ft.", "100 Ft."]let inches = ["0 In.", "1 In.", "2 In.", "3 In.", "4 In.", "5 In.", "6 In.", "7 In.", "8 In.", "9 In.", "10 In.", "11 In.", "12 In."]func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 2}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if component == 0 { return feet.count } else { return inches.count}}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if component == 0 {return feet[row]} else {return inches[row]}}}class TrackPickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {let manufacturers = ["Atlas True Track", "Atlas Code 100", "Atlas Code 83", "Bachmann Nickel Silver", "Bachmann Steel Alloy", "Kato", "Life-Like Trains Code 100", "LIfe-Like Trains Power-Loc", "Peco Code 100", "Peco Code 83", "Peco Code 75", "Shinohara Code 100", "Shinohara Code 70", "Walthers"]func numberOfComponents(in pickerView: UIPickerView) -> Int {        return 1    }func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return manufacturers.count    }func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        return manufacturers[row]    }}

Is it possible to combine UITapGestureRecognizer with pickerView didSelectRow?

$
0
0

I decided to add a tap gesture on my pickerview, is it possible to combine UITapGestureRecognizer with UiPickerView didSelectRow?

'''@objc func tappedToSelectRow(tapRecognizer: UITapGestureRecognizer) {

    if tapRecognizer.state == .ended {    let rowHeight = mainPicker.rowSize(forComponent: 0).height    let selectedRowFrame = mainPicker.bounds.insetBy(dx: 0, dy: (mainPicker.frame.height - rowHeight) / 2.0)    let userTappedOnSelectedRow = (selectedRowFrame.contains(tapRecognizer.location(in: mainPicker)))        if userTappedOnSelectedRow {            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {            self.clearResults()            if pickerView.tag == 0 {                currentTypeSelection = row                self.selectedSettingType = self.viewModel.settingtype[row]                rslt1.text = self.viewModel.settingtype[row]                rslt1.resignFirstResponder()                currentSizeSelection = 0                mainPicker.isHidden = true                rslt2.text = ""                rslt3.text = ""                SettingType.layer.removeAllAnimations()                StoneShape.isEnabled = true                Clear.isEnabled = true                Clear.alpha = 1                if rslt2.text == ""{                    self.focusButton(button: self.StoneShape)                } else {                    focusButton2()                }                if rslt1.text == "Hand U-Pave"{                    self.rslt2.text = "Round"                    self.focusButton(button: self.StoneSize)                    }                }            }        }    }}

'''

SwiftUI - picker is having freezing when selecting after keyboard is up

$
0
0

I have a picker:

Section(header: Text("About you")) {    TextField("About you", text: $profileViewModel.bio)    Picker(selection: $profileViewModel.education,          label: Text("Education Level")) {           ForEach(Education.levels, id: \.self) { level in                 Text(level).tag(level)           }       }     TextField("Occupation", text: $profileViewModel.occupation) }

When I click on the text field, the keyboard appears, which is fine, but when i click on the picker it takes me to the new screen to pick the value and return to the form. This works fine on my simulator (iPhone 11 Pro Max):

Version 11.6 (921.9.1)SimulatorKit 581.9.1CoreSimulator 704.12.2 

But when I test this on my real device iPhone X - v13.5.1 when i click on the picker after the textfield (keyboard is visible) the app crashes. Im not sure this is a bug?

I then put a ontapGesture to the picker to hide the keyboard:

Picker(selection: $profileViewModel.education,     label: Text("Education Level")) {     ForEach(Education.levels, id: \.self) { level in         Text(level).tag(level)     }}.onTapGesture {    self.hideKeyboard()}

This works sometime, but sometimes still crashes, Even when i connect my device to Xcode and try to get logs, I get no error, the app just freezes?

How to disable UITextField editing but still accept touch?

$
0
0

I'm making a UITextField that has a UIPickerView as inputView. Its all good, except that I can edit by copy, paste, cut and select text, and I don't want it. Only the Picker should modify text field.

I've learned that I can disable editing by setting setEnabled or setUserInteractionEnabled to NO. Ok, but the TextField stop responding to touching and the picker don't show up.

What can I do to achieve it?

How to add UIPickerView in UIAlertController?

$
0
0

Could anyone help me I don't have any idea to do this. I have this class like

import Foundationimport UIKitclass Alert {    func loginAlert(viewController : UIViewController , callback: (result: Bool) -> ()) {        var alert = UIAlertController(title : "Compose",            message : "Fill the following",            preferredStyle: UIAlertControllerStyle.Alert        )        var loginAction = UIAlertAction(title: "Send", style: UIAlertActionStyle.Default){            UIAlertAction in        }        var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel){            UIAlertAction in            callback(result: false);        }        alert.addAction(loginAction)        alert.addAction(cancelAction)        alert.addTextFieldWithConfigurationHandler { (textField) -> Void in            textField.secureTextEntry = true            textField.placeholder = "Message"        }        viewController.presentViewController(alert, animated: true, completion: nil)    }}

I read about addTextFieldWithConfigurationHandler it seems it only just for textfield, I wonder how could I do this. Could anyone help me, any comment and suggestion would do. Thanks in advance.


Is there any way to add UIPickerView into UIAlertController (Alert or ActionSheet) in Swift?

$
0
0

I'm totally new to swift (and iOS programming at all), but I started messing around with it (it wasn't a good idea when everything is still beta version :D). So I tried to figure it out by myself, but still nothing. Even tried to add subview containing picker without any success. So can any one help me?

Anonymous closure arguments cannot be used inside a closure that has explicit arguments

$
0
0

So I'm trying to create a Picker in SwiftUI that uses every item of an array. Xcode says "Anonymous closure arguments cannot be used inside a closure that has explicit arguments" when I try to let it use the item of the array (as visible in the code)

import SwiftUIstruct TimerPicker: View {    @State var selectedTime = 0    let availableMinutes = Array(1 ... 59)    private let pickerStyle = SegmentedPickerStyle()    var body: some View {        VStack {            Picker(selection: $selectedTime, label: Text("")) {                ForEach(0 ..< availableMinutes.count) {_ in                    Text("\(self.availableMinutes[$0]) min")                }            }            .labelsHidden()        }    }

Thanks in advance for every answer.

xcode11 how to give a selected option an action, in a PickerView. So that when I select an option in the selected array, I can perform an action to it

$
0
0

For example I select in the PickerView ( country: Scotland, City: Aberdeen ) once I have selected both options in a picker view, I would select a button and have that action take me to another page with information about Scotland, Aberdeen specifically.

What I am trying to do is have my PickerView options take me to another page contained with data specific with those options selected. This is what I have coded so far.

import UIKitclass GrapplingViewController: UIViewController {    @IBOutlet weak var trainingTextField: UITextField!    @IBOutlet weak var areaTextField: UITextField!    @IBOutlet weak var focusTextField: UITextField!    let training = ["Skill Reciting", "Sparring"]            let area = ["Takedowns", "Top Battle", "Bottom Battle", "Survival"]            let focus = ["Full Training", "Specific Training"]            var trainingPickerView = UIPickerView ()            var areaPickerView = UIPickerView ()            var focusPickerView = UIPickerView()   override func viewDidLoad() {          super.viewDidLoad()          title = "Grappling"                trainingTextField.inputView = trainingPickerView                areaTextField.inputView = areaPickerView                focusTextField.inputView = focusPickerView                trainingTextField.placeholder = "Select training type"                areaTextField.placeholder = "Select start position"                focusTextField.placeholder = "Select your focus"                trainingTextField.textAlignment = .center                areaTextField.textAlignment = .center                focusTextField.textAlignment = .center                trainingPickerView.delegate = self                trainingPickerView.dataSource = self            areaPickerView.delegate = self            areaPickerView.dataSource = self                focusPickerView.delegate = self            focusPickerView.dataSource = self                trainingPickerView.tag = 1                areaPickerView.tag = 2                focusPickerView.tag = 3    }            }        extension GrapplingViewController: UIPickerViewDataSource, UIPickerViewDelegate {            func numberOfComponents(in pickerView: UIPickerView) -> Int {                return 1            }            func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {                switch pickerView.tag {                case 1:                    return training.count                    case 2:                        return area.count                case 3:                    return focus.count                default:                    return 1                }            }            func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {                switch pickerView.tag {                case 1:                    return training[row]                case 2:                        return area[row]                case 3:                    return focus[row]                default:                    return "Data not found"            }            }            func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {                switch pickerView.tag {                    case 1:                        trainingTextField.text = training[row]                        trainingTextField.resignFirstResponder()                    case 2:                           areaTextField.text = area[row]                            areaTextField.resignFirstResponder()                    case 3:                        focusTextField.text = focus[row]                        focusTextField.resignFirstResponder()                    default:                        return                }            }         @IBAction func startButton(_ sender: UIButton) {}}

Swift - Visionkit How to edit the color of the buttons "Keep Scan" and "Retake"

$
0
0

I have a problem.I've implemented the visionkit framework in order to detect a text when the camera is used.The problem is that the colors of the buttons: "Keep Scan" and "Retake" are blue. I want them in black color. How can I fix this problem? I paste my code.Thank you in advance!

import UIKitimport Visionimport VisionKitclass ScanText: UIViewController, VNDocumentCameraViewControllerDelegate {    @IBOutlet weak var imageView: UIImageView!    @IBOutlet weak var TextScan: UITextView!    @IBOutlet weak var buttonStartShape: UIButton!    @IBOutlet weak var infoScattaUnaFoto: UILabel!    @IBOutlet weak var copyButtonShape: UIButton!    var textRecognitionRequest = VNRecognizeTextRequest(completionHandler: nil)    private let textRecognitionWorkQueue = DispatchQueue(label: "MyVisionScannerQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .workItem)    var classView = ViewController()    var arrayText = String()    override func viewDidLoad() {        super.viewDidLoad()        imageView.layer.cornerRadius = 15        imageView.clipsToBounds = true        TextScan.layer.cornerRadius = 15        TextScan.clipsToBounds = true        copyButtonShape.layer.cornerRadius = 25        copyButtonShape.clipsToBounds = true        buttonStartShape.layer.cornerRadius = 25        buttonStartShape.clipsToBounds = true        TextScan.isEditable = true        setupVision()    }    @IBAction func TakePicture(_ sender: Any) {        let scannerViewController = VNDocumentCameraViewController()        scannerViewController.delegate = self        present(scannerViewController, animated: true)    }    private func setupVision() {        textRecognitionRequest = VNRecognizeTextRequest { (request, error) in            guard let observations = request.results as? [VNRecognizedTextObservation] else { return }            var detectedText = ""            for observation in observations {                guard let topCandidate = observation.topCandidates(2).first else { return }                print("text \(topCandidate.string) has confidence \(topCandidate.confidence)")                detectedText += topCandidate.string                detectedText += "\n"            }            DispatchQueue.main.async {                self.TextScan.isHidden = false                 self.infoScattaUnaFoto.isHidden = true                self.copyButtonShape.isHidden = false                self.buttonStartShape.setTitle("Ripeti", for: .normal)                self.TextScan.text += detectedText                self.TextScan.flashScrollIndicators()            }        }        textRecognitionRequest.recognitionLevel = .accurate    }    private func processImage(_ image: UIImage) {        imageView.image = image        recognizeTextInImage(image)    }    private func recognizeTextInImage(_ image: UIImage) {        guard let cgImage = image.cgImage else { return }        TextScan.text = ""        textRecognitionWorkQueue.async {            let requestHandler = VNImageRequestHandler(cgImage: cgImage, options: [:])            do {                try requestHandler.perform([self.textRecognitionRequest])            } catch {                print(error)            }        }    }    func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {        /* guard scan.pageCount >= 1 else {         controller.dismiss(animated: true)         return         }*/        for i in 0 ..< scan.pageCount {            let img = scan.imageOfPage(at: i)            processImage(img)        }        let originalImage = scan.imageOfPage(at: 0)        print(originalImage)        //let newImage = compressedImage(originalImage)        controller.dismiss(animated: true)    }    func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {        print(error)        controller.dismiss(animated: true)    }    func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {        controller.dismiss(animated: true)    }    func compressedImage(_ originalImage: UIImage) -> UIImage {        guard let imageData = originalImage.jpegData(compressionQuality: 1),            let reloadedImage = UIImage(data: imageData) else {                return originalImage        }        return reloadedImage    }    //MARK: By tapping on this button, I pass all the data.    @IBAction func CopyText(_ sender: Any) {        let vc = (storyboard?.instantiateViewController(identifier: "SpeakDetail") as? ViewController)!        vc.textscannerized = TextScan.text        self.navigationController?.pushViewController(vc, animated: true)    }}

This is the image

How to add a border to a UIPickerView?

$
0
0

How would you add a border to a UIPickerView? Cant seem to find any property for it. Is there some kind of work around?

I actually have two UIPickerViews next to each other, if possible I would like to get a thin white border around the both of them!

Viewing all 592 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>