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

Source type 1 not available

$
0
0

I have an app for iPhone and iPad, and when I try to load an UIPickerViewController in a UIPopoverController for iPad I get the Exception "Source type 1 not available". getting the problem even though using the device.

@try {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;

        self.tempComp = component;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            [self presentModalViewController:imagePicker animated:YES];
        }else {
            // We are using an iPad
            popoverController=[[UIPopoverController alloc] initWithContentViewController:imagePicker];
            popoverController.delegate = self;

            [popoverController presentPopoverFromRect:component.bounds inView:component permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Camera Non Disponibile" message:@"La camera non è disponibile" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }
}
@catch (NSException *exception) {
    NSLog(@"Cattura eccezione %@", exception);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Eccezione" message:[NSString stringWithFormat:@"%@", exception] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
    [alert show];
}

UIPicker View Rotate Support

$
0
0

I have a universal iOS 6 Application that supports both landscape and portrait orientations.

I have a view that consists of a UIPickerView at the bottom and a label near the top.

On an iPad or iPad Mini there's enough space for the UIPickerView to rotate. However the UIPickerView consumes the entire screen area on an iPhone (both 4 inch and 3.5 inch screens).

I'm sure it doesn't help I have a Tab Bar at the bottom.

Example image

Is there anyway I could EITHER shorten/shrink my UIPickerView or force portrait-only in this view?

Populating a UIPickerView with data from UITableView

$
0
0

So I have a UITableView on one ViewController which held rows of data then a PickerView on another ViewController that I want to show each line from the TableView.

So far I have a UITableView with 130 cells, each cell having a title and description:

three TableView Cells

I then have a UIPickerView on a different ViewController that I need to be populated with the data from the TableView.

I didn't add the TableView cells/data programmatically, instead I edited each cell in storyboard so it looks like:

each cell with 2 labels

Is there a way of doing this or would i have to change the TableView by adding the data programmatically?

Thanks for any help you can give

I've tried adding the TableView to an OutletCollection but wouldn't know where to go from there.

iOS, UIPickerView create programmatically, empty view, delegates work

$
0
0

@Hey everybody,

I have trouble w/ UIPickerView. I'm planning to create a view controller which should allow user to specify the one of the next day. PickerView should show strings like "wed, 1 Dec", "thu, 2 dec", etc The problem is PickerView is empty (PickerView doesn't show any string). In spite of delegates methods return necessary count of strings and the strings themselves.

Image of empty PickerView - LINK

Below is my code.

.h

@interface OMSDatePickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic        ) NSInteger     amountOfDays;
@property (nonatomic        ) CGFloat       cellHeight;

@end

.m

#import "OMSDatePickerViewController.h"

@interface OMSDatePickerViewController () {
    NSMutableArray * dateForChoose;
    NSInteger datePickerActiveIdx;

    UIPickerView *dPicker;
}

@end

- (void)viewDidLoad
{
    NSLog(@"viewDidLoad");

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    dateForChoose = [[NSMutableArray alloc] init];

    dPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(5, 5, 200, 150)];  

    [self.view setFrame: CGRectMake(xPos, yPos, WIN_WIDTH, WIN_HEIGHT)];
    [self.view setAlpha:1.0];
    [self.view setBackgroundColor:[UIColor grayColor]];
    [[self.view layer] setCornerRadius:5.0f];
    [[self.view layer] setBorderWidth:2.0f];
    [[self.view layer] setMasksToBounds:YES];
    [self.view setContentMode:UIViewContentModeScaleToFill];

    // Creating the list of dates
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"EEE',' dd MMM";

    [dateForChoose removeAllObjects];

    // Add some data for demo purposes.
    NSDate *curDate = [NSDate date];
    NSString *str;
    for (NSInteger i = 0; i< amountOfDays; i++, curDate = [curDate dateByAddingTimeInterval:60*60*24]) {
        str = [df stringFromDate:curDate];
        [dateForChoose addObject:str];
    }


    [dPicker setDataSource: self];
    [dPicker setDelegate: self];

    dPicker.showsSelectionIndicator = YES;

    [self.view addSubview:dPicker];


    datePickerActiveIdx = 0;

    NSLog(@"%@", dPicker);
}

and delegates methods

// Number of components.
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// Total rows in our component.
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent: %d", [dateForChoose count]);
    return [dateForChoose count];
}

// Display each row's data.
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString *str = [dateForChoose objectAtIndex: row];
    NSLog(@"%@", [dateForChoose objectAtIndex: row]);
    return [dateForChoose objectAtIndex: row];
}

// Do something with the selected row.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"You selected this [%2d, %2d]: %@", row, component, [dateForChoose objectAtIndex: row]);
    NSLog(@"count - %d", [dateForChoose count]);
    datePickerActiveIdx = row;
}

Interesting things when I try to rotate wheel "didSelectRow" is called and always return row == 0 and show:

[55215:c07] You selected this [ 0, 0]: Wed, 04 Dec

[55215:c07] count - 4

Any ideas?

Addition: the same code work well if it's copied to the implementation of internal function of some UIViewController. For example it's button event handler and the code is called by pressing this button.

WHAT IS IT???*

PS: working log

[18241:907] viewDidLoad
[18241:907] <UIPickerView: 0x1cd944a0; frame = (5 5; 190 162); layer = <CALayer: 0x1cd94990>>
[18241:907] viewWillAppear
[18241:907] numberOfRowsInComponent: 4
[18241:907] numberOfRowsInComponent: 4
[18241:907] Wed, 04 Dec
[18241:907] Thu, 05 Dec
[18241:907] Fri, 06 Dec
[18241:907] Sat, 07 Dec
[18241:907] viewDidAppear

SwiftUI Picker with Enum Source Is Not Enabled

$
0
0

I'm trying to understand the new SwiftUI picker style, especially with data from a source other than an array. I have built a picker with an enum. I first made a simple app with only the picker and associated enum. This works as expected.

Strangely, when I copy and paste that code into another app with other controls in the form, the picker seems to be inactive. I see it, but cannot click it.

Here's the first app (the picker works):

struct ContentView: View {

    @State private var selectedVegetable = VegetableList.asparagus

    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker(selection: $selectedVegetable, label: Text("My Vegetables")) {
                        ForEach(VegetableList.allCases) { v in
                            Text(v.name).tag(v)
                            //use of tag makes no difference
                        }
                    }
                }
            }
            .navigationBarTitle("Picker with Enum")
        }
    }
}

enum VegetableList: CaseIterable, Hashable, Identifiable {
    case asparagus
    case celery
    case shallots
    case cucumbers

    var name: String {
        return "\(self)".map {
            $0.isUppercase ? " \($0)" : "\($0)" }.joined().capitalized
    }
    var id: VegetableList {self}
}

Here's the app with other controls (picker does not work).

struct Order {
    var includeMustard = false
    var includeMayo = false
    var quantity: Int = 1
    var avocadoStyle = PepperoniStyle.sliced
    var vegetableType = VegetableType.none
    var breadType = BreadType.wheat
}

struct OrderForm: View {

    @State private var order = Order()
    @State private var comment = "No Comment"
    @State private var selectedVegetable = VegetableType.asparagus
    @State private var selectedBread = BreadType.rye

    func submitOrder() {}

    var body: some View {
        Form {
            Text("Vegetable Ideas")
                .font(.title)
                .foregroundColor(.green)
            Section {
                Picker(selection: $selectedVegetable, label: Text("Vegetables")) {
                    ForEach(VegetableType.allCases) { v in
                        Text(v.name).tag(v)
                    }
                }
                Picker(selection: $selectedBread, label: Text("Bread")) {
                    ForEach(BreadType.allCases) { b in
                        Text(b.name).tag(b)
                    }
                }
            }

            Toggle(isOn: $order.includeMustard) {
                Text("Include Mustard")
            }

            Toggle(isOn: $order.includeMayo) {
                Text("Include Mayonaisse")
            }

            Stepper(value: $order.quantity, in: 1...10) {
                Text("Quantity: \(order.quantity)")
            }

            TextField("Say What?", text: $comment)

            Button(action: submitOrder) {
                Text("Order")
            }
        }
        .navigationBarTitle("Picker in Form")
        .padding()

    }
}

enum PepperoniStyle {
    case sliced
    case crushed
}

enum BreadType: CaseIterable, Hashable, Identifiable {
    case wheat, white, rye, sourdough, seedfeast
    var name: String { return "\(self)".capitalized }
    var id: BreadType {self}
}

enum VegetableType: CaseIterable, Hashable, Identifiable {
    case none
    case asparagus
    case celery
    case shallots
    case cucumbers
    var name: String {
        return "\(self)".map {
            $0.isUppercase ? " \($0)" : "\($0)" }.joined().capitalized   
    }
    var id: VegetableType {self}
}

Xcode 11 Beta 7, Catalina Beta 7 There is no behavior difference between Preview and Simulator .I must be missing something simple here. Any guidance would be appreciated.

How to prevent buttons to be triggered while dragging the UIPickerView?

$
0
0

I created a custom action sheet that contains one UIPickerView and two buttons (see the image below).

As I drag the roll downwards, my finger (I represented it over the screenshot) presses the button when it “hovers” it.

Eventually I release my finger over the cancel button therefore the cancel event will be fired (of course, same applies to the Ok button).

What should I do to this for not to occure?

enter image description here

My code to create various action sheets in my app is as follows:

/**
 Creates and present action sheet
 */
public func createAndPresentActionSheet(_ parent: UIViewController, title: String, message: String, tag: PickerDataSource, _ completion: @escaping ((_ action: UIAlertAction)->())) {

    let vc = UIViewController()
    vc.preferredContentSize = CGSize(width: 250,height: 200)

    let pickerView = UIPickerView()
    pickerView.isExclusiveTouch = true
    pickerView.tag = tag.rawValue
    pickerView.delegate   = parent as? UIPickerViewDelegate
    pickerView.dataSource = parent as? UIPickerViewDataSource
    vc.view.addSubview(pickerView)
    pickerView.stitchWithConstraints(to: vc.view)

    var row = 0
    switch tag {
    case .gas:                      row = -1 + GasStation.carGas.rawValue

    case .averageSpeed:             row = -1 + Int(GasStation.carAverageSpeed*1e-3)
    case .consumptionPer100km:      row = -1 + Int(GasStation.carGasConsumptionPer100km)
    case .tankVolume:               row = -1 + Int(GasStation.carGasTankVolume)
    case .usualVolumeRefill:        row = -1 + Int(GasStation.carGasUsualRefill)

    case .databaseMinimumFreshness: row = 0
    }

    print("\(#function): row = \(row)")

    if row < 0 { row = 0 }

    print("\(#function): row = \(row) once fixed from being negative")

    pickerView.selectRow(row, inComponent: 0, animated: true)



    let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
    alert.setValue(vc, forKey: "contentViewController")
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in

        if let tvc = parent as? UITableViewController {
            // Reload from data source
            tvc.tableView.reloadData()

            // Force display
            //tvc.tableView.setNeedsDisplay()
        }
        // Call completion
        return completion(action)
    }))
    alert.addAction(UIAlertAction(title: "Annuler", style: .cancel, handler: nil))
    parent.present(alert, animated: true)
}

How to make an UIPickerView with a Done button?

$
0
0

I am having difficulties to make an UIPickerView with a done button to appear when the users taps a UITextField. This is my code so far. Everything builds fine, but when I tap the text field, the keyboard appears, not the picker.

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {


@IBOutlet var textField1: UITextField!

let pickerData = ["11", "12", "13"]





@IBAction func textButton(sender: AnyObject) {

    let picker: UIPickerView
    picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    picker.backgroundColor = .whiteColor()

    picker.showsSelectionIndicator = true
    picker.delegate = self
    picker.dataSource = self

    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")

    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    textField1.inputView = picker
    textField1.inputAccessoryView = toolBar




}



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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 pickerData.count
}

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField1.text = pickerData[row]
}

func donePicker() {

    textField1.resignFirstResponder()

}




}

How to present JSON array in UIPickerView in alphabetical order?

$
0
0

I have a UIPickerView that gets data from JSON and presents it in two columns, one that shows two columns, producer and product using the following:

if let url = URL(string: "https://www.example.com/example"),
                let data = try? Data(contentsOf: url),
                let tmpValues = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:String]] {
                let tempCategories = tmpValues?.reduce(into: [String:[String]](), { (dict, value) in
                    if let producer = value["producer"], let product = value["product"] {
                        dict[producer, default:[]].append(product)
                    }
                })
                for category in (tempCategories ?? [:]) {
                    allCategories.append(Category(name: category.key, items: category.value))
                }
                pickerView.reloadAllComponents()
            }

The issue is while the JSON presents the array in alphabetical order, the PickerView presents the array in random orders every time it is opened, how can this be fixed.


Picker Text color in DarkMode

$
0
0

How do set the text in a Picker control to a light color for iOS13 darkmode

To support DARKMODE on IOS13 you need to set the text color to a colour that the system can change. But on the inspector, there is no ability to set the Picker text to any color.

There must be a simple way to do this but I cannot find it. Using Attributed text is NOT the solution.

Swift UIPickerView defaults to last option regardless of selected option

$
0
0

I have a UIPickerView that when tapping the done button, keeps selecting the last option of the Array. I can tap on either the UITextField or a button I'm using that assigns the UITextField as the first responder. My code is as follows:

Edit. I should also mention that I'm using Xcode 11 GM Seed if that was to make a difference. I tested a clean version of the code shown below on a separate project with nothing else and it is displaying the same behavior.

@IBOutlet weak var sortTypeTextField: UITextField!

var selectedSortOption = String()

let sortOptions = [
        USER_REVIEWS_SORT_OPTION_DATE,
        USER_REVIEWS_SORT_OPTION_LIKES,
        USER_REVIEWS_SORT_OPTION_DISLIKES
    ]

sortOptions above is an array of Strings located in a different file but for the purpose of this question I’ll add here:

let USER_REVIEWS_SORT_OPTION_DATE = "Date"
let USER_REVIEWS_SORT_OPTION_LIKES = "Number of Likes"
let USER_REVIEWS_SORT_OPTION_DISLIKES = "Number of Dislikes"
let DONE_TOOLBAR_BUTTON_TITLE = "Done"

I have a function setupUI which I call in viewDidLoad along with the value for the sortTypeTextField. The value is the first String in the array when the viewController first loads.

override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
}

func setupUI() {
    sortTypeTextField.text = sortOptions[0]
    createSortPicker()
    createPickerToolbar()
}

func createSortPicker() {
    let sortPicker = UIPickerView()
    sortPicker.delegate = self
    sortTypeTextField.inputView = sortPicker
}

func createPickerToolbar() {
    let toolBar = UIToolbar()
    toolBar.sizeToFit()
    let doneButton = UIBarButtonItem(title: DONE_TOOLBAR_BUTTON_TITLE, style: .plain, target: self, action: #selector(dismissKeyboard))
    toolBar.setItems([doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    sortTypeTextField.inputAccessoryView = toolBar
}

@objc override func dismissKeyboard() {
    view.endEditing(true)
}

I’m also using a button to display the UIPicker as shown here:

@IBAction func sortRatingsButtonWasTapped(_ sender: Any) {
    sortTypeTextField?.becomeFirstResponder()
}

As shown below, I want for the sortTypeTextField value to change to the selected option but for some reason when tapping the Done button in the toolbar, the text shown is always the third String in the array regardless if I have chosen the first, the second or the third.

extension ReviewsViewController: UIPickerViewDelegate, UIPickerViewDataSource {

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

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedSortOption = sortOptions[row]
        sortTypeTextField.text = selectedSortOption
    }

}

Populate PickerView with data from Firebase

$
0
0

I have just created a firebase database which consists of having a question and 4 choices of answers and a correct answer. I am struggling to populate the picker view with the data from firebase. I have some functions which shows data from the item label which is the question and this does sort of populate however not fully. I need to implement the functions within the pickerview to populate the choices of answers. How would I go across doing this as currently the picker view is getting data from an array. The array consists of holding a question and a choice of 4 answers and a correct answer, however I need to populate the picker view from firebase.

class QuestionsViewController: UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var usernamelabel: UILabel! //sets username label
    @IBOutlet weak var Next: UIButton! //next button
    @IBOutlet weak var itemLabel: UILabel! //item user has selected
    @IBOutlet weak var Question: UILabel! //sets question label
    @IBOutlet weak var pickerview: UIPickerView! //sets picker view

    public var totalQuestions: Int = 0 //sets total question to 0
    public var currentQuestion = 0  //sets current question to 0
    public var totalCorrect: Int = 0 //sets totalcorrect to 0
    var itemSelected: String = "" //item selected
    var LabelText = String()
    let Exam = Questions() //uses the questions class for instances

    var ref: FIRDatabaseReference!
    var refHandle: UInt!




    override func viewDidLoad() {
         super.viewDidLoad() //when the app is loaded
        usernamelabel.text = LabelText //username
        ref = FIRDatabase.database().reference()
        refHandle = ref.observe(.value, with: { (snapshot)in
            let dataDict = snapshot.value as! [String: AnyObject]
            print (dataDict)
        })


        itemLabel.text = "" //loads the item label of whats selected
        //totalQuestions = quest.count //load the count of the array
       // itemSelected = Exam.quiz[currentQuestion][1] //initially when loaded first item is selected
       // Question.text = Exam.quiz[currentQuestion][0] //first element in first row of array

    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1 //return one component from the picker
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{



        return (Exam.quiz[0].count - 2) //6 columns but only need 4
        //array is 6 and minus 2
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{




        let answers:[String] = Array(Exam.quiz[currentQuestion][1...4]) // which 4 columns to show
        return answers[row] //returns the answer

    }

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

        let answers:[String] = Array(Exam.quiz[currentQuestion][1...4]) //calculates what the item you selected is called
        itemSelected = answers[row]

    }

    @IBAction func NextAction(_ sender: Any){

        ref.child("Questions").child("Q\(currentQuestion)").observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let quest = value?["Question"] as? String ?? ""
            self.Question.text = quest

            // ...
        }) { (error) in
            print(error.localizedDescription)
        }

       // currentQuestion = currentQuestion //moves onto next question and increments

        if(itemSelected == Exam.quiz[currentQuestion - 1][5]){ //checks if item selection is same as column 6
            totalCorrect += 1
            itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions)
        }

        if(currentQuestion < Exam.quiz.count) { // if the current question is lower than the count/size of array
            pickerview.reloadAllComponents()
            itemSelected = Exam.quiz[currentQuestion][1]
            Question.text = Exam.quiz[currentQuestion][0]
        } else {
            pickerview.isHidden = true
            Question.text = "You have finished"
            Next.isHidden = 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

I can't set the uipickerview datasource and delegate from an outside file

$
0
0

I can't seem to set my outside pickerview datasource and delegate to my main view. Is there away I can set it? I want to keep my pickerview in a separate file due to other future views that might use it

This is my custom picker view

final class LenghtPickerView: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {

    let feet = Array(4...7)
    let inches = Array(1...11)

    private var textFieldBeginEdited: UITextField?

    var selectedValue: String {
        get {
            return "\(feet[selectedRow(inComponent: 0)]) ft \(inches[selectedRow(inComponent: 0)]) 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 String(feet[row])
        } else {
            return String(inches[row])
        }
    }
}

and in my main view declaring it private let lenghtPickerView = LenghtPickerView() also tried private let lenghtPickerView: LenghtPickerView = LenghtPickerView()

cant set the datasource and delegate in order for the data to be render

lenghtPickerView.delegate = self
lenghtPickerView.dataSource = self 

iOS UIPickerView - Appearance

How do I change the text color of UIPickerView with multiple components in Swift?

$
0
0

Below code will change the font colour of the picker view of all 3 components. However, it crash when I try to spin the wheel. I think it has to do with the didSelectRow function. Maybe the two function have to be nested somehow? Any idea?

    func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    var attributedString: NSAttributedString!
    if component == 0 {
        attributedString = NSAttributedString(string: a.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    if component == 1 {
        attributedString = NSAttributedString(string: b.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    if component == 2 {
        attributedString = NSAttributedString(string: c.text!, attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    }
    return attributedString
}


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

    switch component {
    case 0:
        aOutput.text = a[row]      -->  **Code breaks**
    case 1:
        bOutput.text = b[row]
    case 2:
        cOutput.text = c[row]
    default:
        10
    }

Is there a way to stop UIDatePicker from scrolling/rotating?

$
0
0

So i want to replicate choosing a date in calendar app, i create a view that is showed/hidden if user taps on date label but if user taps on date label and flics picker and then taps on label to hide it you can still hear and feel picker scrolling/rotating.

I have tried this separately and combine:

datePicker.isHidden = true

datePicker.isEnabled = false

datePicker.date = selectedDate

datePicker.setDate(selectedDate, animated: false)

I think this can be achieved with removing UIDatePicker and adding it again to View but i would not like to go that path.

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.

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?

Detect when UIPickerView starts changing / moving

$
0
0

I'm trying to react to the event that a UIPickerView started moving (not when the row was already selected).

I have searched throughout the delegate methods, and none helped. I also tried to register a notification, but couldn't figure out any that would notify as the user puts his finger on the component and starts scrolling.

Any ideas of what alternatives are there?

How can I make separate picker view in one view controller?

$
0
0

My question about picker view. I have two textfield and these are connect picker view but when I try to make selection these two textfields text become same. I already try make tag for picker view but it didn't work. Here my code for better understand.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldCellTeslim", for: indexPath) as! TextFieldCellTeslim
        let datePickerTeslim = UIPickerView()
        datePickerTeslim.delegate = self
        datePickerTeslim.dataSource = self
        datePickerTeslim.backgroundColor = .white
        cell.dateTextFieldTeslim.inputView = datePickerTeslim
        datePickerTeslim.tag = indexPath.row
        return cell
    }
    if indexPath.section == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldCell", for: indexPath) as! TextFieldCell
        let datePicker = UIPickerView()
        datePicker.delegate = self
        datePicker.dataSource = self
        datePicker.backgroundColor = .white
        cell.dateTextField.inputView = datePicker
        datePicker.tag = indexPath.row
        return cell
    }

These code show us connection of picker view.

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

            secilenTarih = tarihArray[row]
            let path = IndexPath.init(row: pickerView.tag, section: 2)
            let cell = tableView.cellForRow(at: path) as? TextFieldCell
            cell!.dateTextField.text = secilenTarih



            let pathTeslim = IndexPath.init(row: pickerView.tag, section: 3)
            let cellTeslim = tableView.cellForRow(at: pathTeslim) as? TextFieldCellTeslim
            cellTeslim!.dateTextFieldTeslim.text = secilenTarih



    }
    if component == 1 {

            secilenSaat = saatArray[row]
            let path = IndexPath.init(row: pickerView.tag, section: 2)
            let cell = tableView.cellForRow(at: path) as? TextFieldCell
            cell!.dateTextField.text = secilenTarih + "  " + secilenSaat



            let pathTeslim = IndexPath.init(row: pickerView.tag, section: 3)
            let cellTeslim = tableView.cellForRow(at: pathTeslim) as? TextFieldCellTeslim
            cellTeslim!.dateTextFieldTeslim.text = secilenTarih + "  " + secilenSaat

    }
}

And here my picker view extension. I want to make separate selectable of these two textfield.How can I make it? I hope I asked clearly.

Viewing all 593 articles
Browse latest View live


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