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

Fixed labels in the selection bar of a UIPickerView

$
0
0

In the clocks application, the timer screen shows a picker (probably a UIPicker in UIDatePickerModeCountDownTimer mode) with some text in the selection bar ("hours" and "mins" in this case).

(edit) Note that these labels are fixed: They don't move when the picker wheel is rolling.

Is there a way to show such fixed labels in the selection bar of a standard UIPickerView component?

I did not find any API that would help with that. A suggestion was to add a UILabel as a subview of the picker, but that didn't work.


Answer

I followed Ed Marty's advice (answer below), and it works! Not perfect but it should fool people. For reference, here's my implementation, feel free to make it better...

- (void)viewDidLoad {
    // Add pickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
    [pickerView release];
    CGSize pickerSize = [pickerView sizeThatFits:CGSizeZero];
    CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
    #define toolbarHeight           40.0
    CGFloat pickerTop = screenRect.size.height - toolbarHeight - pickerSize.height;
    CGRect pickerRect = CGRectMake(0.0, pickerTop, pickerSize.width, pickerSize.height);
    pickerView.frame = pickerRect;

    // Add label on top of pickerView
    CGFloat top = pickerTop + 2;
    CGFloat height = pickerSize.height - 2;
    [self addPickerLabel:@"x" rightX:123.0 top:top height:height];
    [self addPickerLabel:@"y" rightX:183.0 top:top height:height];
    //...
}

- (void)addPickerLabel:(NSString *)labelString rightX:(CGFloat)rightX top:(CGFloat)top height:(CGFloat)height {
#define PICKER_LABEL_FONT_SIZE 18
#define PICKER_LABEL_ALPHA 0.7
    UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
    CGFloat x = rightX - [labelString sizeWithFont:font].width;

    // White label 1 pixel below, to simulate embossing.
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, top + 1, rightX, height)];
    label.text = labelString;
    label.font = font;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.opaque = NO;
    label.alpha = PICKER_LABEL_ALPHA;
    [self.view addSubview:label];
    [label release];

    // Actual label.
    label = [[UILabel alloc] initWithFrame:CGRectMake(x, top, rightX, height)];
    label.text = labelString;
    label.font = font;
    label.backgroundColor = [UIColor clearColor];
    label.opaque = NO;
    label.alpha = PICKER_LABEL_ALPHA;
    [self.view addSubview:label];
    [label release];
}

Show UIPickerView text field is selected, then hide after selected

$
0
0

I am trying to create a text box that when it is selected a UIPickerView opens up with choices to select from. Once selected, the UIPickerView hides and the selected item is displayed in the text box. I tried different pieces of code I found online but I just can't get it to work. If someone can suggest a complete code for this or tell me what I am doing wrong in my code, that would be super awesome. Thanks so much.

Here is my code:

@IBOutlet var textfieldBizCat: UITextField!
@IBOutlet var pickerBizCat: UIPickerView! = UIPickerView()

var bizCat = ["Cat One", "Cat Two", "Cat Three"]


override func viewDidLoad() {
    super.viewDidLoad()

    var bizCatCount = bizCat.count

    self.textfieldBizCat.inputView = pickerView

}

// returns the number of 'columns' to display.
func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int{
    return 1
}

// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
    return bizCat.count
}

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

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    textfieldBizCat.text = "\(bizCat[row])"

}

UIPickerview as inputview to uitextfield in swift shows Keyboard for working code

$
0
0

Did anybody noticed uitextfield- pickerview behaves differently with .ipa installation for an existing working code.

I am new to IOS development. I have working code with more than 20 view controllers. Where I used UIPickerView as inputview to UITextField which is populated on a network call. The application was tested using .ipa file as well as directly installing through Xcode for a couple of iterations. Everything was working fine.

Recently When  I created the new .IPA file, none of the picker views were working after installing. All the view controllers were showing the keyboard when I tap the text field instead of the picker view selection.  Whereas the same build is working fine when I directly install/run from Xcode to mobile.

Since its application-wide, I noticed my Archive scheme > Build configuration was somehow set to Release. Based on some stack overflow answers, I have updated the archive build configuration to Debug. After that created a new .ipa file,  All the Viewcontrollers were showing the picker views correctly except one view controller. I have readded the text field and set the textfield delegate again. still no luck

I tried almost all the possibilities.  

I am completely stuck. Not sure why all of a sudden the working code is broken.

Code snippet:

@IBOutlet weak var selectAccountTB: UITextField! ...

func textFieldDidBeginEditing(_ textField: UITextField) {
        activeTextField = textField
       self.selectedItem = ""   if (activeTextField  == selectAccountTB ) {
        let toolBar = UIToolbar.init().addToolBarHandler(selectorDone: #selector(pickerDoneTapped), selectorCancel: #selector(pickerCancelTapped))
        self.activeTextField.isUserInteractionEnabled = true
        self.activeTextField.inputAccessoryView = toolBar
        if (self.activeTextField == self.selectAccountTB ) {
            self.activeTextField.inputView = self.accountPickerView
        }
    }

}



extension QTPViewController : UIPickerViewDelegate , UIPickerViewDataSource {
         
        func numberOfComponents(in pickerView: UIPickerView) -> Int {     return 1   }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            var count = 1
            if self.activeTextField == self.selectAccountTB {
                count = self.accountList.count
            } else if self.activeTextField == self.selectPayeeBankTB {
                count = self.payeeBankValueList.count
            }
            return count
        }
            func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            var rowValue:String!
            if self.activeTextField == self.selectAccountTB
            {
                rowValue = self.accountList[row]
            } else if self.activeTextField == self.selectPayeeBankTB {
                rowValue = self.payeeBankValueList[row]
            }
            return rowValue
        }
        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
            if self.activeTextField == self.selectAccountTB {
                if (!accountList.isEmpty) {
                    self.selectedItem = self.accountList[row]
                    print("Selected Item " , self.accountList[row])
                }
            }
        }

}

textfield delegate is set in storyboard.

While debugging noticed control is not coming to textFieldDidBeginEditing() at all i=n failed scenarios.

Any direction to fix the issue is much appreciated.

How to disable the view while using UIPickerView

$
0
0

I have been using UIPickerView, my question is simple, how to disable the view when picker view is showing, so that we can ensure user are not changing anything in view. I have tried with setuserInteractinEnabled: method but it is disabling picker view too.. Any idea..?

Can I make an array of arrays?

$
0
0

Im trying to create an array inside an array inside an array. Then use a UIPickerView with 3 components, each for the respective array. The reason I used arrays is because the data is organized like this:

var array1 = [
     "2"
[       "2"
           ["2.5","2.5"],
        "1-1/12"
           ["2.5","2.375"]],
     "3"
[       "2-1/2"
           ["3.375", "3.25"],
[       "2"
           ["3.375", "3"]]]

I've tried making dictionaries to call from (easier for UIPickerView) but the [(key:value)] combo won't work with tuples.

var dict: [(size: String, outlets: (outlet1: String, measure1: String, measure2: String))] = [
("2", ("1-1/2","2.5","2.375"))
]

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

There's not much info about arrays inside arrays or dicts inside dicts.

The source data is from a chart that looks like this:

          --> outlet1 --> value1, value2
size1 --> --> outlet2 --> value1, value2
          --> outlet3 --> value1, value2

          --> outlet1 --> value1, value2
size2 --> 
          --> outlet2 --> value1, value2

Outlets can be the same String as size.

How do I get a list of countries in Swift ios?

$
0
0

I've already seen two similar questions to mine, but the answers for those questions do not work for me. I have an old project with a list of countries manually typed out inside a set of square brackets.

I can easily use this in my pickerView but I'm wondering if there is a more efficient way to do this?

I will be using the list of countries in a UIPickerView.

is there a uipickerview delegate method like scrollviewDidScroll?

$
0
0

I have a customized UIPickerview and I do not want to use a datepicker. I want to implement the feature where when a user scrolls down/up the hours, the AM/PM component switches while the hour is scrolling. This means that I need to switch it before pickerView didSelectRow is called. Is there a way to do this?

Thanks

How to make UIPickerView.viewForRow highlighted in the center , the reset row gray?

$
0
0

How to make it more nicely?

Like the following image: the center row is highlighted, the rest row gray.

000

Here is code:

extension ViewController: UIPickerViewDelegate{

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let info = BeatScalar.generalRates[row]
        let general = GeneralRateItem(info.cn, info.ita, info.val)
        // gray every row
        general.unselected()
        decorateView(pickerView, row: row)
        return general
    }


    // Here is the logic 
    func decorateView(_ picker: UIPickerView, row: Int){

        var frame = picker.frame
        frame.origin.y = frame.origin.y + frame.size.height * 0.42
        frame.size.height = frame.size.height * 0.16

        let mini = max(row-1, 0)
        //   19 is total number
        let maxi = min(18, row+1)
        for i in mini...maxi{
            if i != row, let item = picker.view(forRow: i, forComponent: 0) as? GeneralRateItem{
                let f = item.convert(item.frame, to: picker)
                if frame.intersects(f) == false{
                    // highlight the center row
                    item.selected()
                }
            }
        }
    }

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


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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {       // 19 is total number
        return 19
    }
}

more code in github

I need to use func pickerView(_ pickerView: UIPickerView, viewForRow, because

22

The code above works fine, the drawback is that it calculates much, and hard coded with some math.

I don't really know the logic. I think the logic result is just the opposite.

while Xcode always reports,

[Assert] Attempted to call -cellForRowAtIndexPath: on the table view while it was in the process of updating its visible cells, which is not allowed. Make a symbolic breakpoint at UITableViewAlertForCellForRowAtIndexPathAccessDuringUpdate to catch this in the debugger and see what caused this to occur. Perhaps you are trying to ask the table view for a cell from inside a table view callback about a specific row? Table view: ; layer = ; contentOffset: {0, 19}; contentSize: {314, 836}; adjustedContentInset: {127.66666666666667, 0, 127.33333333333331, 0}; dataSource: ; layer = >>

How to improve the code?


I have an other idea,

access the pickerView's subview to do it

3333

How to do it more neatly?


Change color of selectedRow in UIPickerView, also when rolling

$
0
0

I have to change the color of the selected row in a UIPickerView.

I did managed to change the color, i know that the question already have several replies, anyway those do not satisfy me: with those implementation, the animation of the pickerview is glitchy and i don't like it.

This is the code of the current solution

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    var label: UILabel
    if view == nil {
      label = UILabel()
    } else if view is UILabel {
      label = view as! UILabel
    } else {
      label = UILabel()
    }

    let title: NSAttributedString
    if self.model?.selectedValue == row {
      title = UIPickerView.attributedString(with: .selectedRow, text: "\(model?.years[row] ?? 0)")
    } else {
      title = UIPickerView.attributedString(with: .unselectedRow, text: "\(model?.years[row] ?? 0)")
    }

    label.attributedText = title
    return label
}

And when the user scrolls, I reload the components.

But as you can see in the images below, when a user scroll, the green field moves and there is a fraction of seconds in which the green label is below the selector indicator and the selected row is black.

pickerview while scrollingafter scroll but before the reload

What I'd like to have is that everything inside the selector indicator is green while what outside keeps the default shades of grey.

How can I implement this?

How to Scroll to Specific Row in UIPickerView In iOS Swift 3

$
0
0

I have a UIPickerView with values 0...250. There is 2 Components in UIPickerView. In First component i am displaying these values. but i want to detect scrolling method of the UIPickerView. because when pickerView appears the value I would like to display is 75. means pickerView is scroll to row number 75. and user can scroll up and down the picker with values 0...250. I have tried this code in UIPickerViewtitleForRow row: Int method

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

in this case when pickerView appears the selected value is 75. Below is exactly what i want

enter image description here

but the problem is that on scrolling pickerView my app crash with following error

[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

anyone help me please thanks in advance :-)

UIPickerView selection input Swift 4 or 5

$
0
0

I have a UIPickerView that selects from an array of states and the last item in the array is “outside the US”. When the last item in the array is selected I want to show another input option for country.

Currently I have the country input set to hidden in viewDidLoad.

This is my attempt at trying to get this to work, but it keeps causing a crash on selection of the last item.

var stateOptionsList = ["", "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District Of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "Outside The United States"]

let outsideOfUS = stateOptionsList[statePicker.selectedRow(inComponent: 52)] as String

print(outsideOfUS)

if selectStateInput.text == outsideOfUS {
    countryContainer.isHidden = false
} else {
    countryContainer.isHidden = true
}

I put the let outsideOfUs var in the pickerView didSelectRow. Not sure if this is where I am supposed to put this.

Pass data back to UIPickerView

$
0
0

I'm creating timer app and I want user be able to edit existing timers. For, example, when User click on specific timer, he can edit hours, minutes and seconds, which I get initially from UIPickerView.

I'm using this code to get hours, minutes and seconds for new timers:

    var hour: Int = 0
    var minutes: Int = 0
    var seconds: Int = 0
    var name: String = ""

    var totalSeconds: Int {
        return hour * 3600 + minutes  * 60 + seconds
    }

}
     extension TimerSelectViewController: UIPickerViewDelegate, UIPickerViewDataSource {

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

         func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
             switch component {
             case 0:
                 return 25
             case 1, 2:
                 return 60
             default:
                 return 0
             }
         }

         func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
            return pickerView.frame.size.width/4
         }

         func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
             switch component {
             case 0:
                 return "\(row) hr"
             case 1:
                 return "\(row) min"
             case 2:
                 return "\(row) sec"
             default:
                 return ""
             }
         }
         func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
             switch component {
             case 0:
                 hour = row
             case 1:
                 minutes = row
             case 2:
                 seconds = row
             default:
                 break;
             }
         }

But how I can pass data back to UIPickerView when user want to edit a timer and not creates a new timer?

UIPicker selectRow not working - what's wrong with this code?

$
0
0

I'm trying to set a default value for the UIPickerView. However, no matter which value I set it to, it always defaults to 1. The method below loads the picker just fine, and I can select it. So, what am I doing wrong? Here's the code.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    arrayNo = [[NSMutableArray alloc] init];
    [arrayNo addObject:@" 1 "];
    [arrayNo addObject:@" 2 "];
    [arrayNo addObject:@" 3 "];
    [arrayNo addObject:@" 4 "];
    [arrayNo addObject:@" 5 "];

    [pickerView selectRow:4 inComponent:0 animated:YES];
    mlabel.text= [arrayNo objectAtIndex:[pickerView selectedRowInComponent:0]];    

}

Picker's DataSource methods:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    mlabel.text = [arrayNo objectAtIndex:row];
    NSNumberFormatter * f = [[NSNumberFormatter alloc] init];

    [f setNumberStyle:NSNumberFormatterDecimalStyle];

    NSNumber * myNumber = [f numberFromString:[arrayNo objectAtIndex:row]];

    [f release];

    prefs = [NSUserDefaults standardUserDefaults];

    NSInteger myInteger = [myNumber integerValue];


    // save level
    [prefs setInteger:myInteger forKey:@"myInt"];

    // saving it all
    [prefs synchronize];


}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [arrayNo count];
}

How to make multi column picker in xamarin forms?

$
0
0

I need to create a picker which have 2 columns in xamarin forms like timepicker. I am using Picker control. Is there any way through which we can make multiple columns in Picker?

Why are unrelated autolayout constraints changing when I am adding a UIPickerView?

$
0
0

When I add my picker view of images to the view, it changes the autolayout constraints of other objects that are not constrained in any way to the picker view.

Before adding the picker view: before

After adding the picker view: after

Here, I'm adding the mainContainer (UIView that just covers the screen except for the top where the app title is) and primaryHeaderLabel (UILabel that says "NEW TRAY"). As you can see, none of those autolayout constraints contain anything from the imagePickerView, but they're still being moved.

view.addSubview(mainContainer)
    mainContainer.setAnchors(top: titleLabel.bottomAnchor, paddingTop: 5, bottom: view.bottomAnchor, paddingBottom: 0, left: view.leftAnchor, paddingLeft: 0, right: view.rightAnchor, paddingRight: 0, centerX: nil, centerY: nil, width: 0, height: 0)

mainContainer.addSubview(primaryHeaderLabel)
    primaryHeaderLabel.setAnchors(top: mainContainer.topAnchor, paddingTop: 20, bottom: nil, paddingBottom: 0, left: mainContainer.leftAnchor, paddingLeft: 40, right: mainContainer.rightAnchor, paddingRight: 40, centerX: nil, centerY: nil, width: 0, height: 0)

Here are the code bits related to the imagePickerView. I have tried adding the picker view to the main view instead of the mainContainer, but got the same result:

let imagePickerView: UIPickerView = {
        let pickerView = UIPickerView()
        return pickerView
    }()


let pickerItems: [String] = [
        "pickerPink",
        "pickerBlue",
        "pickerPurple",
        "pickerYellow"
    ]


mainContainer.addSubview(imagePickerView)
    imagePickerView.setAnchors(top: primaryHeaderLabel.topAnchor, paddingTop: 0, bottom: primaryHeaderLabel.bottomAnchor, paddingBottom: 0, left: nil, paddingLeft: 0, right: mainContainer.rightAnchor, paddingRight: 40, centerX: nil, centerY: nil, width: 60, height: 0)
    imagePickerView.delegate = self
    imagePickerView.dataSource = self

Picker view delegate methods and data source:

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

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

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))

    imageView.image = UIImage(named: pickerItems[row])

    view.addSubview(imageView)

    return view

}

Can someone help me with this? Any help would be greatly appreciated.


What is an Alternative to the UIPickerView from IOS in android?

$
0
0

I am trying to reproduce the IOS UIPickerView functionality but in android.

In IOS you can set this UIPickerView as an input type of the keyboard. I need this same type of interaction but in android.

UPDATE: When I say input type I mean the UIPickerView simply replaces the keyboard view. So if a textfield were clicked the UIPickerView would open instead of the Keyboard. Hope that clears stuff up!

How to have in xamarin.ios the pickers look-a-like xamarin forms?

$
0
0

I have a project that is running natively with xamarin.ios, but the problem is that I need the selector to work as if it were a widget that uses xamarin forms(see the image below), I mean a text box that autofills with the selection, and below At the bottom of the page are the items that can be selected.

Does anyone have a shape that is similar to the sea? The native picker doesn't fit me at all.

see a example

Passing updated array data to uipickerview

$
0
0

Still pretty new to swift, I was having some trouble passing updated data into the pickerview. I'm receiving the "index out of range" error. I have a suspicion that the uipickerview is seeing the empty array, even though the arrays are getting updated. Any help is much appreciated.

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var nameDisplay: UILabel!
    @IBOutlet weak var ageDisplay: UILabel!
    @IBOutlet weak var emailDisplay: UILabel!
    @IBOutlet weak var pickerView: UIPickerView!



    @IBOutlet weak var txtfirstName: UITextField!
    @IBOutlet weak var txtAge: UITextField!
    @IBOutlet weak var txtEmail: UITextField!
    @IBOutlet weak var lblValidationMessage: UILabel!

    var ages = [Int]()
    var emailAddresses = [String]()
    var firstNames = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        //     lblValidationMessage.isHidden = true
        // Do any additional setup after loading the view.

        //links txtAge to the UITextField class, which gives access to func textfield
        txtAge?.delegate = self
        pickerView?.dataSource = self
        pickerView?.delegate = self
    }

    // restricts the values possible to input in txtAge.text

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let allowedCharacters = "1234567890"
        let allowedCharcterSet = CharacterSet(charactersIn: allowedCharacters)
        let typedCharcterSet = CharacterSet(charactersIn: string)
        return allowedCharcterSet.isSuperset(of: typedCharcterSet)
    }

    @IBAction func addUserButton(_ sender: UIButton) {

        //validation of data in the text boxes

        lblValidationMessage.isHidden = true
        if let firstName = txtfirstName.text, firstName == "" {
            lblValidationMessage.isHidden = false
            lblValidationMessage.text = "Enter Your Name"
            return
        }

        if let age = txtAge.text, age == "" {
            lblValidationMessage.isHidden = false
            lblValidationMessage.text = "Please enter a numerical age"
            return
        }

        if let email = txtEmail.text, email.isEmpty {
            lblValidationMessage.isHidden = false
            lblValidationMessage.text = "Please enter an email address"
            return
        }


        //MARK: Adds entries to the 3 arrays

        firstNames.append(txtfirstName.text!)

        //Converts string to int, the age array requires INT
        let age:Int! = Int(txtAge.text!)
        ages.append(age)

        emailAddresses.append(txtEmail.text!)



        txtfirstName.text = ""
        txtAge.text = ""
        txtEmail.text = ""

        //Brings focus back to First Name text field
        txtfirstName.becomeFirstResponder()
    }

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

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

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

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

}

I see only ?-s when using 2 pickerviews in Swift on the same view controller, how to fix this?

$
0
0

I have been trying to figure out this problem for hours, now I have only one small problem remaining:

I use 2 UI pickers on one view controller, and when I try to select one (aka I'm clicking into the textfield) all I see is question marks, but if I click on one of them, the text will appear in the textfield. I just don't see what am I choosing in the picker.

I already tried using normal pickerviews, I used tags for each pickers, but nothing seemed to work. I know how it should work, I watched a ton of tutorials, but something is still missing. Can you please help me? Thank you!

Here is the code:

import UIKit

class SelectionViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    @IBOutlet weak var ageTextField: UITextField!
    @IBOutlet weak var weightTextField: UITextField!

    @IBOutlet weak var genderTextField: UITextField!
    @IBOutlet weak var lifeStyleTextField: UITextField!

    let picker1 = UIPickerView()
    let picker2 = UIPickerView()

    var genders = ["Male", "Female"]
    var lifeStyle = ["Sitting", "Normal", "Active"]

    override func viewDidLoad() {
        super.viewDidLoad()

        picker1.dataSource = self
        picker1.delegate = self

        picker2.dataSource = self
        picker2.delegate = self

        genderTextField.inputView = picker1
        lifeStyleTextField.inputView = picker2
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView == picker1 {
            return genders.count
        } else {
            return lifeStyle.count
        }
    }

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

        if pickerView == picker1 {
            return genders[row]
        } else if pickerView == picker2{
            return lifeStyle[row]
        }
        else {
            print("No pickerview selected.")
        }
        return ("Pickeview not selected")
    }

        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if pickerView == picker1 {
                genderTextField.text = genders[row]
                self.view.endEditing(false)
            } else if pickerView == picker2{
                lifeStyleTextField.text = lifeStyle[row]
                self.view.endEditing(false)
            }
            else {
                print("Love love love I want your love")
            }
        }
}

And here's the thing I see:

enter image description here

iOS 13 UIPrinter quickly goes out of existence

$
0
0

User selects a printer (UIPrinter) using the UIPrinterPickerController. Once selected, that UIPrinter is used for output (print(to:) throughout the app and persists for subsequent launches of the app. From iOS 9 through iOS 12, this method has worked well.

However, under iOS 13, the following happens:

The UIPrinter is always available when used for the first time. But once used, after a short period of time (less than a minute) the UIPrinter seems to go out to existence. This happens when using the Xcode Printer Simulator or an actual physical printer via AirPrint.

Here's the Xcode Console message on the first print - it works:

Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Print-Job successful with warning: Job attributes did not match print document.

Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Release-Job successful with warning: successful-ok (successful-ok)

Here's what happens 1 minute later:

Simulated\032Color\032Laser\032@\032myMac._ipps._tcp.local.: Print-Job failed: Printer "Simulated_Color_Laser_myMac" does not exist.

When this happens, the only way to continue is to re-select the UIPrinter in the PrinterPicker.

Any ideas as to what might be happening here?

Thanks,

Viewing all 593 articles
Browse latest View live


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