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

How to get my data into the PickerViewModel

$
0
0

Using the answer at this link TextInput Field with Pickerview instead of keyboard as a guide, I wrote the code below. I have three UITextFields that I need to configure a picker as input for. The second one is dependent on the selection of the first one, and the third one is dependent on the selection of the second one. I'm at a bit of a loss as to how I get the data into the class PickerViewModel as each UITextField needs different data. The code with my modifications:

    void ConfigurePicker(UITextField pickerTextField)    {        // var pickerTextField = new UITextField();        List<string> theData = new List<string>();        if ((pickerTextField.Placeholder.ToUpper() == "SELECT COMPANY" && dropTextField.Text == "") )        {            var okAlertController = UIAlertController.Create("ERROR", "Please select a company from the company drop down liat.", UIAlertControllerStyle.Alert);            okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));            PresentViewController(okAlertController, true, null);        }else if (pickerTextField.Placeholder.ToUpper() == "SELECT SECTION" && dropTextField2.Text == "")        {            var okAlertController = UIAlertController.Create("ERROR", "Please select a department from the department drop down liat.", UIAlertControllerStyle.Alert);            okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));            PresentViewController(okAlertController, true, null);        }        else        {            var picker = new UIPickerView            {                Model = new PickerViewModel(),                ShowSelectionIndicator = true            };            var screenWidth = UIScreen.MainScreen.Bounds.Width;            var pickerToolBar = new UIToolbar(new RectangleF(0, 0, (float)screenWidth, 44)) { BarStyle = UIBarStyle.Default, Translucent = true };            var flexibleSpaceButton = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);            var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (sender, e) => pickerTextField.ResignFirstResponder());            pickerToolBar.SetItems(new[] { flexibleSpaceButton, doneButton }, false);            pickerTextField.InputView = picker;            pickerTextField.InputAccessoryView = pickerToolBar;        }    }    class PickerViewModel : UIPickerViewModel    {        public List<string> _pickerSource = new List<string>();        public override nint GetRowsInComponent(UIPickerView pickerView, nint component) => _pickerSource.Count;        public override string GetTitle(UIPickerView pickerView, nint row, nint component) => _pickerSource[(int)row];        public override nint GetComponentCount(UIPickerView pickerView) => 1;    }

IOS7 UIPickerView how to hide the selection indicator

$
0
0

How can I hide those 2 lines on the selected row?

enter image description here

How to customize selected entire row background color of UIPickerView, not just background of label

$
0
0

I tried to find a lot of times but nowhere mention about this topic exactly.Could I change the center selected row view background to dark blue like this image?

Many thanks for help!Swift or Objectivec are appreciated.

UIPickerView with dark blue background selected row image

Sorry not enough reputation for embedded image here, this is an image link.

==> Answer.Added solution for easy to read.

I found a very simple solution; by setting UIpickerview background as clear color then add a new UIView (MiddleRowBackground named) at both center horizontal and vertical position of UIPickerView. set height of MiddleRowBackground the same the Cell's height of UIPickerView which defined in optional func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat. Width is the same with UIPickerView.

Picker delegate scrolling method in SwiftUI

$
0
0

I have simple Picker object in my SwiftUI hierarchy:

Picker(selection: $pickerSelection, label: Text("Select your item")) {    ForEach(0 ..< items.count) {        Text("\(self.items[$0].valueCode)")            .tag($0)    }}

I'm using a scrollable Picker in WatchOS app and it works just fine. I'm even getting a Digital Crown rotation capability for free.

What I want to do is to detect when the scrolling started and especially ended (to get last selected value and execute and action with it)

I figure I need to implement sort of Delegate method to read the changes happening to the Picker but I'm not sure how, nor I'm able to find any in the documentation for WKInterfacePicker or just Picker

Any suggestions on how to detect the beginning and end of the scrolling event?

Hide the cursor of an UITextField

$
0
0

I am using a UITextField with a UIPickerView for its inputView, so that when the user taps the text field, a picker is summoned for them to select an option from.

Nearly everything works, but I have one problem: the cursor still flashes in the text field when it is active, which is ugly and inappropriate, since the user is not expected to type into the field and is not presented with a keyboard. I know I could hackily solve this by setting editing to NO on the text field and tracking touches on it, or by replacing it with a custom-styled button, and summoning the picker via code. However, I want to use the UITextFieldDelegate methods for all the event handling on the text field and hacks such as replacing the text field with a button do not permit this approach.

How can I simply hide the cursor on the UITextField instead?

Take data from Enum to show on UIPickerView

$
0
0

I am creating a simple View where there is a UIPickerView and I want to display the choices on the PickerView from an enum. I have created an enum of possible drinks

enum drink{  case coffee  case tea  case cola  case water}

I was wondering how it would be possible to display the drinks in an UIPickerView? I am using Swift 1.2 and Xcode 6.3.1.. Thanks!! :)

Populate UIPickerView data using http request

$
0
0

I have this UIPickerView which will have data yet, but doesn't have data, since I make async http request

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        var dataCount = PickerData.count        return dataCount    }

happens before my data is loaded, how do I populate my PickerData after this function happens? I couldn't find any answers on any website, maybe I'm searching for wrong terms but still, i couldn't do it, i thought about making sync request, but I've read that it is a bad practice, so is there a good way to solve my problem?

Also I want to add, the data might change over time so I want to be able to change PickerView data too.

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


UIPickerView in Container View not resizing when animating container height change

$
0
0

Using IB, I have set up a UIVPicker in a Container View's associated UIViewController. The Container's height is controlled by two auto-layout constraints, one which sets the height to zero, one which sets it the same as the height of its superview. I change the priority of one of the constraints to toggle active/inactive. In IB, the priorities are set so the picker's initial height is zero (full-height constraint priority 750; zero-height constraint priority 751).

When I make the full-height constraint active, I can see it taking effect: the UIPickerView has a colored background. I can see the background expand to the height of the superview. Here's the weird part: The UIPickerView's own subviews (picker titles, selection bars, and so on) are not resizing along with the picker's own background. I can see them all bunched up at the top of the picker display in the top 30 pixels or so. I have verified it is the picker's background I am seeing expand when I toggle the constraints using XCode's ability to display layers when debugging.

If I set the zero-height constraint priority to 749 in IB to allow the full-height constraint to be active and then 'hide' the pickerView after it appears by putting the following in viewDidAppear...

self.pickerContainerViewHeightConstraintZeroHeight.priority = 751;[self.pickerContainerView layoutIfNeeded];

...then the picker contents display correctly. (This is a diagnostic-only solution because the user sees the picker flash and then disappear.) I can then hide and display the picker at will and it continues to look as it should. If I put the same code in viewDidLayoutSubviews or viewWillAppear to try to turn this into a 'real' solutionn, the picker is messed up when I display it.

The following actually does work, but it's really ugly... Set the zero-height constraint priority to 749 in IB to allow the full-height constraint to be active and then...

- (void )viewWillAppear:{     self.pickerContainerView.hidden = YES; }- (void )viewDidAppear:{    self.pickerContainerViewHeightConstraintZeroHeight.priority = 751;    [self.pickerContainerView layoutIfNeeded];    self.pickerView.hidden = NO; }

...which amounts to letting the view be full height when it's built, hiding it using the hidden attribute so the user doesn't see it at first, changing its height to zero, 'showing' it (which the user won't see because the height is now zero) so that when I next change the height to full height, the picker shows correctly.

But there has to be a better way. How do I start with the picker height = 0 and still get it have the correct appearance when it is shown by changing constraints?

Hide Picker View Hide Left Swift

$
0
0

I am trying to hide left up and down arrow. Is there any way to hide left arrow in picker view

Screen shot

Code:

let picker = UIPickerView()picker.tag = tagpicker.delegate = selfpicker.dataSource = selftxtField.inputView = picker

Pickerview is showing empty on second click in the textfield, adn when i press Done or Cancel the App crashes

$
0
0
var gender = ["MALE","FEMALE", "Other"]var genderPicker: UIPickerView! = UIPickerView()

// On the first click in the textfield the gender pickerview works fine, but if i press out and then i press again in the gender textfield the picker appears empty.

// And when i press either cancel or Done to dismiss the picker the app crashes with the below error

Unrecognized selector sent to instance” in swift

This screenhot shows the second time i press in the textfield

override func viewDidLoad() {    super.viewDidLoad()    tableViewHeight.constant = screenHeight * 0.7    // Do any additional setup after loading the view.    let toolBar = UIToolbar()    toolBar.barStyle = UIBarStyle.default    toolBar.isTranslucent = true    toolBar.tintColor = UIColor.systemBlue    toolBar.sizeToFit()    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: "donePicker")    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: "donePicker")    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)    toolBar.isUserInteractionEnabled = true    genderTxtField.delegate = self    genderPicker!.delegate = self    genderPicker!.dataSource = self    genderTxtField.inputAccessoryView = toolBar    self.genderTxtField.inputView = genderPicker}func donePicker() {    genderTxtField.resignFirstResponder()}

// Delegates Methods

extension InsuranceMethodsSemiViewController: UITextFieldDelegate {    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {        genderPicker.isHidden = false        genderTxtField.inputView = genderPicker;        return false    }    func textFieldDidEndEditing(_ textField: UITextField) {        genderPicker.isHidden = true    }}extension InsuranceMethodsSemiViewController: UIPickerViewDelegate {    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        return gender[row]    }func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    genderTxtField.text = gender[row]    self.view.endEditing(true)    pickerView.isHidden = true}}extension InsuranceMethodsSemiViewController: UIPickerViewDataSource {    func numberOfComponents(in pickerView: UIPickerView) -> Int {        return 1    }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return gender.count    }}

Why my pickerview doesn't appear on certain text field?

$
0
0

I have found this video where was shown way for adding picker views with fields to the app. I have added three fields:

@IBOutlet weak var position: UITextField!@IBOutlet weak var emplFilter: UITextField!@IBOutlet weak var locFilter: UITextField!

and also variables which represents current text field and picker:

var currentTextField = UITextField()var currentPicker = UIPickerView()

and also added implementations:

UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource

Added all methods:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        if currentTextField == locFilter{            return location.count        }else if currentTextField == test{            return proffestion.count        }else if currentTextField == emplFilter{            return employer.count        }else{            return 0        }    }    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        if currentTextField == locFilter{            return location[row].name        }else if currentTextField == test{            return proffestion[row].name        }else if currentTextField == emplFilter{            return employer[row].name        }else{            return ""        }    }    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {        if currentTextField == locFilter{            locFilter.text = location[row].name            filters!["location"] = location[row].id            self.view.endEditing(true)        }else if currentTextField == test{            filters!["prof"] = proffestion[row].id            test.text =  proffestion[row].name            self.view.endEditing(true)        }else if currentTextField == emplFilter{            emplFilter.text = employer[row].name            filters!["employer"] = "\(String(describing: employer[row].id))"            self.view.endEditing(true)        }    }    func textFieldDidBeginEditing(_ textField: UITextField) {        self.currentPicker.delegate = self        self.currentPicker.dataSource = self        print("click")        currentTextField = textField        if currentTextField == locFilter{            currentTextField.inputView = currentPicker        }else if currentTextField == test{           currentTextField.inputView = currentPicker        }else if currentTextField == emplFilter{           currentTextField.inputView = currentPicker        }        self.currentPicker.delegate = self        self.currentPicker.dataSource = self    }

and here I have a problem - when I click on position field I don't see any output in logs. I can't understand why it happens, I tried to add another field but it didn't change the situation. I tried to use another array but I also didn't see any picker view. I tried to look for any possible solution in the Internet, but I didn't succeed in it :(

RxSwift - Filter data from tableview from UIPickerView

$
0
0

i try to filter data from my table View. When i select one value from picker View, The data suppose to filter based on the category and the table view should reload with filtered data.here i attach the code

struct RecipeList {let id: Intlet catid: Stringlet name: Stringlet description: Stringlet ingredient: Stringlet step: Stringlet image: Stringlet img: NSData//static var dataSource = BehaviorRelay(value: [RecipeList]())static var items = [RecipeList]()}

here how i fetch data to table View

func setupCellConfiguration() {  let recipeList = Observable.just(RecipeList.items)    recipeList        .bind(to: tableView            .rx            .items(cellIdentifier: RecipeListCell.Identifier,                   cellType: RecipeListCell.self)) { row, recipe, cell in                    cell.configureWithRecipe(recipe: recipe)    }    .disposed(by: disposeBag)}

Here how pick event on picker view

func setupRecipeTypePickerView(textField: UITextField) {    let pickerView = UIPickerView()    pickerView.selectRow(Int(self.selectedRecipeType) ?? 0, inComponent: 0, animated: false)    textField.inputView = pickerView    let recipeType = Observable.of(RecipeType.items)    recipeType.bind(to: pickerView.rx.itemTitles) { (row, element) in        return "\(element.name)"    }    .disposed(by: disposeBag)    pickerView.rx.itemSelected        .subscribe { (event) in            switch event {            case .next(let selected):                selected.row == 0 ? (self.isFilter = false) : (self.isFilter = true)                let recipeType = RecipeType.items[selected.row]                textField.text = recipeType.name                self.selectedRecipeType = recipeType.id                RecipeList.items.append(contentsOf: RecipeList.items.filter({$0.catid == recipeType.id}))            default:                break            }    }    .disposed(by: disposeBag)}

Here how append data from Core data to Model

    func getRecipeList() {    RecipeList.items.removeAll()    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }    let managedContext = appDelegate.persistentContainer.viewContext    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Common.ENTITYNAME)    do {        let result = try managedContext.fetch(fetchRequest)        for data in result as! [NSManagedObject] {            let id = data.value(forKey: "id") as! Int            let catid = data.value(forKey: "catid") as? String ?? "1"            let name = data.value(forKey: "name") as! String            let description = data.value(forKey: "rdescription") as! String            let ingredient = data.value(forKey: "ingredient") as! String            let step = data.value(forKey: "step") as! String            let image = data.value(forKey: "image") as! String            let img = data.value(forKey: "img") as! NSData            let recipe = RecipeList(id: id, catid: catid, name: name, description: description, ingredient: ingredient, step: step, image: image, img: img)            RecipeList.items.append(recipe)        }       // RecipeList.dataSource.accept(RecipeList.items)    } catch {        print("Failed")    }}

I try alot solution from multiple sources, seems does not work. This is my first day learning RXSwift. Usually i didnt use RXSwift, i just simply, create variable for filtered data, then rereload the tableView

PickerView not showing viewForRow - Swift - Programmatically

$
0
0

I'm setting up a UIPickerView and in order to do that I decided to use the method viewForRow of the UIPickerViewDelegate which returns a UIView.

The pickerView shows correctly but the "selected" state of the picker, the one which should represent the element selected with the full alpha gradient doesn't appear.

I can only see the elements when they're NOT in the selected state.

This is the actual code:

class DurationPickerView: UIPickerView {let inView : UIView = {    let view = UIView(frame: .init(x: 0, y: 0, width: 50, height: 50))    let imageView = UIImageView(image: #imageLiteral(resourceName: "infinity").withRenderingMode(.alwaysOriginal))    imageView.tintColor = .white    view.addSubview(imageView)    imageView.fillSuperview()    return view}()let tfView : UIView = {   let view = UIView(frame: .init(x: 0, y: 0, width: 50, height: 50))    let label = UILabel(text: "24h", font: UIFont(name: "avenir-black", size: 20), textColor: .white, textAlignment: .center        , numberOfLines: 0)    view.addSubview(label)    label.fillSuperview()    return view}()}extension DurationPickerView : UIPickerViewDelegate{func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat        {    return 50}func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {    switch row {    case 0:        return inView    default:        return tfView       }    }} extension DurationPickerView : UIPickerViewDataSource{func numberOfComponents(in pickerView: UIPickerView) -> Int{    return 1  }func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{    return 2}}

Setting UITextField's inputView property to a UIPicker not working in Swift

$
0
0

Hello I am trying to pop a UIPickerView view programmatically when user clicks on textfield. I have tried this but it doesn't doing anything, it isn't working. Nothing is happening when I click the textfield

class UserProfileTableViewController: UITableViewController,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource { var itemPicker: UIPickerView! = UIPickerView()    @IBOutlet weak var genderTxtField: UITextField!    var gender = ["MALE","FEMALE"]    override func viewDidLoad() {        super.viewDidLoad()        genderTxtField.delegate = self        itemPicker!.delegate = self        itemPicker!.dataSource = self        itemPicker!.backgroundColor = UIColor.blackColor()        self.genderTxtField.inputView = itemPicker    }    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{        return 1    }    // returns the # of rows in each component..    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{        return gender.count    }    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        return gender[row]    }    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)    {        genderTxtField.text = gender[row]        //.hidden = true;    }    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {        itemPicker.hidden = false        return false    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

UIPickerView get selected value without datasource

$
0
0

What would be the best way to get the value from a PickerView without having a datasource? So i can not read values from i.e. an array.

Current values are just row numbers, that i need to read after user is done with picking.

func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 3}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if component == 0 {        return 300    } else {        return 10    }}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if component == 0 {        return "\(row)."    } else {        return "\(row)"    }}

enter image description here

Using multiple UIPickerViews in dynamic UITableView

$
0
0

I am trying to make use of UIPickerViews, whereby the user can select an "amount"(number) between 1 and 20. In my TableviewCell there is a label and the picker.Before I implemented the PickerViewDelegate and PickerViewDatasource, everything was fine. Since then I cannot even check if my code is right, cause it gives me "Fatal error: Unexpectly found nil..." for the label which has the array soloJobs (Array is not empty). So I guess I am making something fundamentally wrong.

At the end my achievment would be to store the values of the jobAmountPickerin the selAmountArray for given index.

Maybe someone can help.

This is my tableviewcell:

import UIKitvar globalAmount:[String] = []class ProjectCharacterTableViewCell: UITableViewCell,  UIPickerViewDelegate, UIPickerViewDataSource {    var jobAmount: [String] = []    var pickerData = ["1", "2", "3", "4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"]    var selAmountArray: [String] = []    static let identifier = "ProjectCharacterTableViewCell"    @IBOutlet weak var jobLabel: UILabel!    @IBOutlet weak var jobAmountPicker: UIPickerView!     override func awakeFromNib() {        self.pickerData = Array<String>()        self.jobAmountPicker.delegate = self;        self.jobAmountPicker.delegate = self;        super.awakeFromNib()    }     override func setSelected(_ selected: Bool, animated: Bool) {        super.setSelected(selected, animated: animated)        // Configure the view for the selected state    }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return pickerData.count    }    func numberOfComponents(in pickerView: UIPickerView) -> Int {           return 1       }    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent  component: Int) {        let selectedAmount = pickerData[row] as String        selAmountArray.append(selectedAmount)        globalAmount = selAmountArray    }       func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {           return pickerData[row]       }}

And that's my viewController:

import UIKitimport FirebaseDatabaseimport Foundationimport FirebaseFirestoreSwiftimport CodableFirebaseclass ProjectCharacterViewController: UIViewController, UITextFieldDelegate {// MARK: - Properties    @IBOutlet weak var specTxt: UITextField!    @IBOutlet weak var difficultyTxt: UITextField!    @IBOutlet weak var budgetTxt: UITextField!    @IBOutlet weak var tableView: UITableView!    var soloJobs: [String] = []    var jobAmount: [String] = []    var rowBeingEditet : Int? = nil    var indexesNeedPicker: [NSIndexPath]?    var i: Int?    override func viewWillAppear(_ animated: Bool) {        super.viewWillAppear(animated)        getJobs(for: User.current) { (memberJob) in        }    }    override func viewDidLoad() {        tableView.register(ProjectCharacterTableViewCell.self, forCellReuseIdentifier: "ProjectCharacterTableViewCell")        super.viewDidLoad()    }// MARK: - Functions    func getJobs(for user: User, completion: @escaping ([MemberJobsStruct]) -> Void) {         var jobs: [String] = []         let ref = Database.database().reference().child("team").child(user.uid)                 ref.observe(DataEventType.value, with: { snapshot in                    for case let child as DataSnapshot in snapshot.children {                    guard let value = child.value as? [String: Any] else {                        return completion ([])                }                        let memberJob = value["memberJob"] as! String                        jobs.append(memberJob)                        self.soloJobs = self.removeDuplicates(array: jobs)                        DispatchQueue.main.async {                                   self.tableView.reloadData()                               }                    }                 })    }func removeDuplicates(array: [String]) -> [String] {    var encountered = Set<String>()    var result: [String] = []    for value in array {        if encountered.contains(value) {            // Do not add a duplicate element.        }        else {            // Add value to the set.            encountered.insert(value)            // ... Append the value.            result.append(value)        }    }    return result    }      @IBAction func show(_ sender: Any) {        print("SoloJobs: ", soloJobs)        print("Thats the job amount: ", jobAmount)        print("Global amount :", globalAmount)    }}// MARK: - UITableViewDataSourceextension ProjectCharacterViewController: UITableViewDataSource {    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        return soloJobs.count    }    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        let cell = tableView.dequeueReusableCell(withIdentifier: "ProjectCharacterTableViewCell") as! ProjectCharacterTableViewCell        cell.jobLabel.text = soloJobs[indexPath.row]        i = indexPath.row        cell.jobAmountPicker.reloadAllComponents();           return cell        }}// MARK: - UITableViewDelegateextension ProjectCharacterViewController: UITableViewDelegate {    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {     return 60    }}

How to pause the code and wait for an answer from UIAlert on Swift using UIAlertController

$
0
0

I got to say I've searched around for the answer in stack overflow, but couldn't find it so that's why I'm asking it...

**

  • MyProblem:my problem is - I'm making a Pomodoro App, and I let theuser to set the TimeLabel(the time), now if the user is in a session,and he wants to change the time he's able doing that, although if hetries doing that and once he has changed the time and wanna cancelit, the user of-course is able to do that, now the problem is I'mwaiting for the user's answer by using UiAlertController, but amongthat I also use my function that updates the SettingsLabels/Parameters.

**

My Code:my update settings function:

//Updating the UserSettings:func updateSettingsLabels(cell: PickerTableViewCell, rowIndex: Int) {    let identifier = cell.reuseIdentifier    switch identifier {    case T.Identifiers.workIntervalID:        workInterval.text = timesDictionary[rowIndex]        self.workIntervalString = timesDictionary[rowIndex] // set string        let myString = workInterval.text!        oldTime = workInterval.text! // setting up the old time        saveTime(labelText: myString)    case T.Identifiers.shortBreakID:        shortBreak.text = timesDictionary[rowIndex]        self.shortBreakString = timesDictionary[rowIndex] // set string        saveShortBreak(breakText: shortBreak.text!)    case T.Identifiers.longBreakTimeID:        longBreakTime.text = timesDictionary[rowIndex]        self.longBreakString = timesDictionary[rowIndex] // set string        saveLongBreak(longBreakText: longBreakString!)    case T.Identifiers.breakAfterIntervalsID: // after how much intervals we will take a long break        longBreakAfter.text = intervalsDictionary[rowIndex]        self.longBreakAfterIntervals = intervalsDictionary[rowIndex] // set string        saveBreakAfterIntervals(breakAfterIntervals: longBreakAfterIntervals!)    case T.Identifiers.dailyIntervalsID: // daily intervals        dailyIntervals.text = intervalsDictionary[rowIndex]        self.dailyIntervalsString = intervalsDictionary[rowIndex] // set string        saveDailyIntervals(dailyIntervals: dailyIntervalsString!)    default:        print("There was a problem with Switch")    }

my UiAlert Function:

func alertTheUser() {    //If we want to print something on the screen, we use UIAlertController:    let alert = UIAlertController(title: "Do you want to aboard this task?", message: "Once you change the time in a middle of a session, you will reset all tasks.", preferredStyle: .alert)    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (alertToCancel) in        self.userWantToChangeSettings = false        print("Im being changed!")    }))    alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: { (action) in        self.userWantToChangeSettings = true    }))    self.present(alert, animated: true)}

I must inform u guys that I also use UIPicker that lets the user choose the time from optional times, and here's my code for that:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int, forCell cell: PickerTableViewCell) {    if self.timerIsOnFire == true {            self.alertTheUser()    }    updateSettingsLabels(cell: cell, rowIndex: row)    self.delegate?.userSettings(interval: self.workIntervalString, shortBreak:self.shortBreakString, longBreak:self.longBreakString, breakAfterIntervals:self.longBreakAfterIntervals,dailyIntervals:self.dailyIntervalsString )    self.view.endEditing(true)}

SwiftUI - Using CoreData Fetched Result to Populate Picker

$
0
0

I'm following every guide I've seen online to bring in the managed object to the SwiftUI scene with environment and then run a @FetchRequest in the scene, all of it works great.

I can use that result to populate the value of a picker

Heres what I have

CoreData Object

    public class CD_LookupData: NSManagedObject,Identifiable {}extension CD_LookupData {    @nonobjc public class func fetchRequest() -> NSFetchRequest<CD_LookupData> {        return NSFetchRequest<CD_LookupData>(entityName: "CD_LookupData")    }    @NSManaged public var lookluptable: String?    @NSManaged public var primarykeyid: String?    @NSManaged public var value: String?}

SwiftUI View

struct LabledSelectBoxCD: View {    var label: String    var lookupdata: FetchedResults<CD_LookupData>    @Binding var value: Int    var body: some View    {        VStack(alignment: .leading)        {            Picker(selection: $value, label: Text(""))            {                ForEach(lookupdata, id: \.primarykeyid)                { data in                    Text(data.value ?? "Unknown")                }            }        }    }}

Its populates the picker with the values just fine but my default value never works and no value selected is saved.

If I try the same view with just an array of strings it works perfectly.

Any ideas on how I can get it to use the value of primarykeyid for the value of the picker?

Update:

@Binding var value: String

and

Text(data.value ?? "Unknown").tag(data.primarykeyid)

Don't make any changes

multiple pickerview didSelectRow error in Swift

$
0
0

I have 2 pickerviews, 1 pickerview is to select a crypto-currency from an Array and the other pickerview is used to select a currency from an array. The problem I am having is when I run the app on simulator and select the cryptocurreny in cryptoPicker the app it also selects the same array value from currencyPicker and vice a versa. I don't want the array value of 0 to be pulled from both arrays unless it is selected by the user.

@IBOutlet weak var cryptoCurrentRate: UILabel!@IBOutlet weak var currencyLabel: UILabel!@IBOutlet weak var currencyPicker: UIPickerView!@IBOutlet weak var cryptoPicker: UIPickerView!@IBOutlet weak var cryptoLabel: UILabel!var coinManager = CoinManager()override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view.    coinManager.delegate = self    currencyPicker.dataSource = self    currencyPicker.delegate = self    cryptoPicker.dataSource = self    cryptoPicker.delegate = self   }

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {       return 1   }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        if pickerView == currencyPicker {        return coinManager.currencyArray.count        }        if pickerView == cryptoPicker {        return coinManager.cryptoArray.count    }        return 0    }    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        if pickerView == currencyPicker {        return coinManager.currencyArray[row]        }        if pickerView == cryptoPicker {        return coinManager.cryptoArray[row]    }        return ""    }    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {        let selectedCurrency = coinManager.currencyArray[row]        let selectedCrypto = coinManager.cryptoArray[row]        coinManager.fetchCryptoCoin(assetIdBase: selectedCrypto, assetIdQuote: selectedCurrency)    }

}

Viewing all 592 articles
Browse latest View live


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