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

Make UIPickerView in front of Tab Bar

$
0
0

enter image description here

as you can see, my UIPickerView is in back a Tab bar, how to make it in front them? i'm using swift

and also my done button doesn't work to hide the UIView that contain UIPickerView, i'm sure the button connected to an action

here's my doneButton action

@IBAction func doneButtonTapped(sender: AnyObject) {

    self.viewUIPickerView.viewWithTag(1)?.hidden = true

}

Two UIPickerViews in one ViewController

$
0
0

Two PickerViews selectTypeOfWorkChoices& selectLocationChoices do not appear correctly.

A function dismissPickerView() seems working well. However, another function "createPickerView()" has some problems. Although UIpickerviews appear, I cannot see the choices in UIPickerViews and I don't know why.

Could anyone help me figure out what's wrong with my code, please??

@IBOutlet weak var selectTypeOfWorkChoices: UIPickerView!

@IBOutlet weak var selectLocationChoices: UIPickerView!

override func viewDidLoad() {
    super.viewDidLoad()

    createPickerView()
    dismissPickerView()

    }

var typeOfWork = ["--", "a", "b", "c"]

var location = ["--", "A", "B", "C"]

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    var countrows : Int = typeOfWork.count
    if pickerView == selectLocationChoices {
        countrows = self.location.count
    }
    return countrows
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if pickerView == selectTypeOfWorkChoices {
        let titleRow = typeOfWork[row]

        return titleRow
    }
    else if pickerView == selectLocationChoices {
        let titleRow = location[row]

        return titleRow
    }
    return ""
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == selectTypeOfWorkChoices {
        selectedPriority = typeOfWork[row]
        selectTypeOfWork.text = selectedPriority

        self.selectTypeOfWork.text = self.typeOfWork[row]

    }
    else if pickerView == selectLocationChoices {
        locationSelectedPriority = location[row]
        selectLocation.text = locationSelectedPriority

        self.selectLocation.text = self.location[row]

    }


}

var selectedPriority :  String?
var locationSelectedPriority :  String?


func createPickerView() {

    let pickerView = UIPickerView()
    pickerView.delegate = self

    self.selectTypeOfWorkChoices.delegate = self
    self.selectTypeOfWorkChoices.dataSource = self
    self.selectLocationChoices.delegate = self
    self.selectLocationChoices.dataSource = self


        selectTypeOfWork.inputView = selectTypeOfWorkChoices

        selectLocation.inputView = selectLocationChoices



}


@objc func dismissPickerView() {
    let toolBar = UIToolbar()
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title:"Done", style: .plain, target: self, action: #selector(self.dismissKeyboard))
    toolBar.setItems([doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true

    selectTypeOfWork.inputAccessoryView = toolBar
    selectLocation.inputAccessoryView = toolBar
}

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

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

How to change the number of rows in a UIPickerView component based on the selected value in another component

$
0
0

The Google Calendar app has a feature where you can customize when you want a notification to be sent before an event. If you're unfamiliar with it, it looks like this:

Google Calendar Custom Notification

It's essentially a picker view with two components, the first one showing numbers for the user to choose, and the second showing units of time ("minutes", "hours", "days", "weeks"). When the user selects the unit of time, the numbers change. For example, if the user chooses "minutes" as their unit, the first component will show numbers 1 through 60. If they choose "hours", the first component will show 1 through 24. Selecting "days" will show 1 through 28, and "weeks" will show 1 through 4.

I want to develop a similar feature, but when I run my code I get the error "Index out of range". The error occurs in the last function in this chunk of code. In the debug section, the value of "row" is 0. I think the error has to do with the differences in the sizes of the arrays, but I'm not sure. All help is appreciated!

import UIKit
class AlarmSet
{
    func timeIntervals() -> [String]
    {
        return ["minutes", "hours", "days", "weeks"]
    }

    func timeValues(time: String) -> [Int]
    {
        switch time
        {
            case "minutes":
                return Array(1...60)
            case "hours":
                return Array(1...24)
            case "days":
                return Array(1...28)
            case "weeks":
                return [1, 2, 3, 4]
            default:
                return [0]
        }
    }
}

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate 
{

    @IBOutlet weak var addAlarm: UIButton!
    @IBOutlet weak var alarmView: UIPickerView!

    //The first component of the picker displays numbers
    var picker1Options:[Int] = []
    //The second picker displays units of time (minutes, hours, etc.)
    var picker2Options:[String] = []

    override func viewDidLoad()
    {
        super.viewDidLoad()
        alarmView.delegate = self
        alarmView.dataSource = self
        alarmView.delegate?.pickerView?(alarmView, didSelectRow: 0, inComponent: 0)
        alarmView.delegate?.pickerView?(alarmView, didSelectRow: 0, inComponent: 1)

        alarmView.isHidden = true
        let alarm = AlarmSet();

        picker2Options = alarm.timeIntervals()
        let firstValue = picker2Options[0]
        picker1Options = alarm.timeValues(time: firstValue)

        // Do any additional setup after loading the view.
    }

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

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        if component == 1
        {
            return picker2Options.count
        }
        else
        {
            return picker1Options.count
        }
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {
        if component == 0 
        {
            return "\(picker1Options[row])"
        } 
        else 
        {
        return "\(picker2Options[row])"
        }
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if component == 1
        {
            let alarm = AlarmSet();
            //Out of range error is on this next line
            let currentValue = picker2Options[row]
            picker1Options = alarm.timeValues(time: currentValue)
            pickerView.reloadAllComponents()
        }
    }
}

How to prepare UIPickerView with months and years in ios?

$
0
0

I'm working on Preparing UIPickerView with months and year in iOS.

Below is my code.

in viewdidload :

//Array for picker view
monthsArray=[[NSMutableArray alloc]initWithObjects:@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sep",@"Oct",@"Nov",@"Dec",nil];


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
NSString *yearString = [formatter stringFromDate:[NSDate date]];


yearsArray=[[NSMutableArray alloc]init];


for (int i=0; i<13; i++)
{
    [yearsArray addObject:[NSString stringWithFormat:@"%d",[yearString intValue]+i]];
}

myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
[myPickerView selectRow:0 inComponent:0 animated:YES];
[self.view addSubview:myPickerView];

Picker view delegate methods:

// tell the picker how many components it will have
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}

// tell the picker how many rows are available for a given component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSInteger rowsInComponent;
if (component==0)
{
    rowsInComponent=[monthsArray count];
}
else
{
    rowsInComponent=[yearsArray count];
}
return rowsInComponent;
}



- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{

NSString * nameInRow;
if (component==0)
{
    nameInRow=[monthsArray objectAtIndex:row];
}
else  if (component==1)
{
    nameInRow=[yearsArray objectAtIndex:row];
}

return nameInRow;
}


// tell the picker the width of each row for a given component
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
CGFloat componentWidth ;

if (component==0)
{
    componentWidth = 100;
}
else  {
    componentWidth = 100;
}

return componentWidth;
}

And i got the following output :

PickerImage

But in the current year , the months from Jan to Oct have expired. How to disable those years in my picker only for the current year dynamically. Those months should be available for the remaining years.

Actually the real output is,

enter image description here

In above, the expired months in the current year should be disabled in UI.

Any comments or suggestions would be appreciated.

Thank you in advance.

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

$
0
0

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

class ViewController: UIViewController {

//MARK: Properties


@IBOutlet weak var layoutLengthPicker: UIPickerView!
@IBOutlet weak var layoutWidthPicker: UIPickerView!
@IBOutlet weak var trackPicker: UIPickerView!

let layoutLengthPickerDelegate = DimensionsPickerDelegate()
let layoutWidthPickerDelegate = DimensionsPickerDelegate()
let trackPickerDelegate = TrackPickerDelegate()

override func viewDidLoad() {
    super.viewDidLoad()

    layoutLengthPicker.delegate = layoutLengthPickerDelegate
    layoutLengthPicker.dataSource = layoutLengthPickerDelegate

    layoutWidthPicker.delegate = layoutWidthPickerDelegate
    layoutWidthPicker.dataSource = layoutWidthPickerDelegate

    trackPicker.delegate = trackPickerDelegate
    trackPicker.dataSource = trackPickerDelegate


    // Do any additional setup after loading the view, typically from a nib.
}


//MARK: Actions



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


}

class DimensionsPickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {

let feet = ["0 Ft.", "1 Ft.", "2 Ft.", "3 Ft.", "4 Ft.", "5 Ft.", "6 Ft.", "7 Ft.", "8 Ft.", "9 Ft.", "10 Ft.", "11 Ft.", "12 Ft.", "13 Ft.", "14 Ft.", "15 Ft.", "16 Ft.", "17 Ft.", "18 Ft.", "19 Ft.", "20 Ft.", "21 Ft.", "22 Ft.", "23 Ft.", "24 Ft.", "25 Ft.", "26 Ft.", "27 Ft.", "28 Ft.", "29 Ft.", "30 Ft.", "31 Ft.", "32 Ft.", "33 Ft.", "34 Ft.", "35 Ft.", "36 Ft.", "37 Ft.", "38 Ft.", "39 Ft.", "40 Ft.", "41 Ft.", "42 Ft.", "43 Ft.", "44 Ft.", "45 Ft.", "46 Ft.", "47 Ft.", "48 Ft.", "49 Ft.", "50 Ft.", "51 Ft.", "52 Ft.", "53 Ft.", "54 Ft.", "55 Ft.", "56 Ft.", "57 Ft.", "58 Ft.", "59 Ft.", "60 Ft.", "61 Ft.", "62 Ft.", "63 Ft.", "64 Ft.", "65 Ft.", "66 Ft.", "67 Ft.", "68 Ft.", "69 Ft.", "70 Ft.", "71 Ft.", "72 Ft.", "73 Ft.", "74 Ft.", "75 Ft.", "76 Ft.", "77 Ft.", "78 Ft.", "79 Ft.", "80 Ft.", "81 Ft.", "82 Ft.", "83 Ft.", "84 Ft.", "85 Ft.", "86 Ft.", "87 Ft.", "88 Ft.", "89 Ft.", "90 Ft.", "91 Ft.", "92 Ft.", "93 Ft.", "94 Ft.", "95 Ft.", "96 Ft.", "97 Ft.", "98 Ft.", "99 Ft.", "100 Ft."]

let inches = ["0 In.", "1 In.", "2 In.", "3 In.", "4 In.", "5 In.", "6 In.", "7 In.", "8 In.", "9 In.", "10 In.", "11 In.", "12 In."]

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

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if component == 0 { return feet.count } else { return inches.count}

}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if component == 0 {return feet[row]} else {return inches[row]}

}
}

class TrackPickerDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {

let manufacturers = ["Atlas True Track", "Atlas Code 100", "Atlas Code 83", "Bachmann Nickel Silver", "Bachmann Steel Alloy", "Kato", "Life-Like Trains Code 100", "LIfe-Like Trains Power-Loc", "Peco Code 100", "Peco Code 83", "Peco Code 75", "Shinohara Code 100", "Shinohara Code 70", "Walthers"]

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

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

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

}

Why am I unable to press the UIButton inside of my UIPickerView?

$
0
0

I have a UIPickerView with a UIToolBar item added to it (Done Button). But when I select the button, it's supposed to print something to the console via #selector(dismissKeyboard), and yet it doesn't.

I'm relatively new to Swift and I'm doing everything programmatically, so I'm just having a bit of a hard time figuring out why I cannot interact with the button that's added as a subview to my pickerView.

Here is the relevant code that I'm working with... Please let me know if you need more info...

As a side, I already assigned the delegate and datasource for the pickerView, and I call the createToolBar() function inside the viewDidLoad.

    var timerImage = UIButton()
    var timer = Timer()
    var timerDisplayed = 0
    let image1 = UIImage(named: "stopwatch")
    let timePicker = UIPickerView()

    @objc func dismissKeyboard(){
        print("PickerView Dismissed")
        view.endEditing(true)
    }

    func pickerViewConstraints(){
        timePicker.anchor(top: nil, leading: view.safeAreaLayoutGuide.leadingAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: view.safeAreaLayoutGuide.trailingAnchor)
    }

    func createToolBar(){
        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(dismissKeyboard))
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))

        toolBar.sizeToFit()
        toolBar.setItems([doneButton], animated: true)
        toolBar.isTranslucent = false
        toolBar.isUserInteractionEnabled = true

        timePicker.addSubview(toolBar)
        self.view.bringSubviewToFront(toolBar)    
    }

    @objc func timeClock(){
        view.addSubview(timePicker)
        pickerViewConstraints()
        timePicker.backgroundColor = .white

        DispatchQueue.main.async {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.Action), userInfo: nil, repeats: true)
            self.timerImage.setImage(nil, for: .normal)
        }
    }

Removing UIPickerView when button is pressed swift

$
0
0

How can I dismiss a uipickerview view using swift? I have created the UIPickerView in UITableView as I want it to be populated with the elements in the UITableView. Then I have just a UIButton appear on the screen. I want it so that the UIPickerView will be removed when the button is pressed.

//being able to delete a row
// this method handles row deletion
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    // Edit Button
    let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in

        //saving the index of section
        self.contactIndex = indexPath.section

        //            print(self.tableViewData[indexPath.section].exerciseData[indexPath.row])
        print(self.tableViewData[indexPath.section])

        //setting exercisesInSelectedWorkout to exercise names within workout
        self.exercisesInSelectedWorkout = self.tableViewData[indexPath.section].exerciseData

        //creating uipicker
        var UIPicker: UIPickerView = UIPickerView()
        UIPicker.delegate = self as UIPickerViewDelegate
        UIPicker.dataSource = self as UIPickerViewDataSource
        let hello = UIPicker

        //Calling UIPicker done buttons:
        self.view.addSubview(self.TheDoneButton)
        self.TheDoneButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.TheDoneButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            self.TheDoneButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor ,constant: 40),
            ])

        //adding uipicker to screen
        self.view.addSubview(UIPicker)
        UIPicker.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            UIPicker.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            UIPicker.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -150),
            //UIPicker.widthAnchor.constraint(equalToConstant: self.view.frame.width - 64)
            ])

        //locking tableview
        tableView.alwaysBounceVertical = false
    })
    editAction.backgroundColor = UIColor.blue


    // Delete Action UITableView
    let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in

        //removing data from tableview
        self.tableViewData.remove(at: indexPath.section)
        tableView.deleteSections(IndexSet(integer: indexPath.section), with: .top)

        //Deleting Data from CoreData
        CoreDataManager.sharedInstance.deleteDataFromCoreData(contact: self.contacts[indexPath.section])
        print("Items removed from Table View")
        print("Row Deleted")
    })
    deleteAction.backgroundColor = UIColor.red
    return [editAction, deleteAction]
}


//UIPICKER Done button function (what happens when done is pressed)
@objc func uipickerDoneButtonPressed(){

How do I change the color of the text in a UIPickerView under iOS 7?

$
0
0

I'm aware of the pickerView:viewForRow:forComponent:reusingView method, but when using the view it passes in reusingView: how do I change it to use a different text color? If I use view.backgroundColor = [UIColor whiteColor]; none of the views show up anymore.

Swift5 Several input methods for textfield (PickerView & System alphabetic keyboard) simulteniously

$
0
0

The is a method inside the

custom cell class

and all components are initiated in the beginning:

// MARK: - Initialize
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

self.addSubview(textFieldView)
self.textFieldView.delegate = self

    self.superview?.addSubview(tablePicker)
    self.textFieldView.inputView = tablePicker
    self.tablePicker.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
    self.tablePicker.delegate = self
    self.tablePicker.dataSource = self
    self.tablePicker.isHidden = false
}

I have also configured all constraints and call it from superview? , because it's a custom cell class. Before I did change the input method for UITextField the keyboard appeared. However, now UIViewPicker shows up.

Question:Is it possible to make both inputs for the same UITextField simultaneously?

UIPickerView in VC - Pass data from function didSelectRow to UITextField.text in a UIView

$
0
0

I have separate files for my UIView and its correspondant UIViewController. I have a UITextField in my UIVew and I want the text displayed in the field to be displayed immediately when I select a row from the UIPickerView. Now I have end editing and start editing again in order for my UITextField.text property to update to the content selected in the row.

I have set up my code like this:

UITextField in UIView:
        let presentSelectedCaloriesTextField: UITextField = {
       let textField = UITextField()
        textField.layer.borderColor = UIColor.black.cgColor
        textField.layer.borderWidth = 1
        textField.addTarget(self, action: #selector(handleSelectCalories), for: .editingDidBegin)
        return textField
    }()

Handler:

@objc func handleSelectCalories() {
    selectCaloriesDelegate?.handleSelectCalories(for: self)
}

Delegate:

UIView.selectCaloriesDelegate = self

In my UIViewController:

    //    MARK: - Handle selected calories delegate
    func handleSelectCalories(for view: RaceView) {

//        Create picker view for selection of calories
        let challengeWeighedCaloriesPicker = UIPickerView()

//        Set datasoruce and delegate of picker view to this vc send and receive content
        challengeWeighedCaloriesPicker.dataSource = self
        challengeWeighedCaloriesPicker.delegate = self

//        Set the picker view as the input keyboard for select calories textfield
        view.presentSelectedCaloriesTextField.inputView = challengeWeighedCaloriesPicker

//        UPDATES ONLY AFTER I'VE SELECTED A ROW AND END AND START EDITING IN TEXTFIELD AGAIN
        view.presentSelectedCaloriesTextField.text = selectedCalories
    }

Someone knows how to this so that the UITextField.text property gets set immediately whenever I scroll through the rows of the UIPickerView?

UIPickerView is lagging on Scroll

$
0
0

I'm using pickerview in project it's working fine on date picker but when I'm using array list in that pickerview it's lagging on iPhone as well as simulator. Any help with this issue? Thanks in advance.

How to change frame size of UIImagePicker when I get photo from photoLibrary or camera?

$
0
0

I want change frame size of UIImagePicker when I get photo from photoLibrary or camera. It only allow square size frame to crop it but I have to give photo in 5:3 ratio in. How can I do it in Swift?

Text

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var pickerLabel: UIPickerView!

func selectPhoto(){
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.sourceType = .photoLibrary
    picker.allowsEditing = true
    present(picker,animated: true, completion: nil)

    image = imageFromGallery

    imageView.image = imageFromGallery
}



func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageFromGallery = (info[.editedImage] as? UIImage)!
    image = imageFromGallery
    imageView.image = imageFromGallery
    self.dismiss(animated: true, completion: nil)
}

I call selectPhoto() to get photos.

There are some questions like my question but I didn't find exact solution for Swift.

How to change the Font size in UIPickerView?

$
0
0

I have one UIPickerView. This is having nearly 200 items, each items has long texts, so, i want to resize the UIPickerView's font size. How can i change it? It is possible? Can any one help me? Thanks !

Yuva.M

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.


How do I send UIPickerView selected row to another ViewController

$
0
0

I would like to send the selected UIPickerViews row to another view controller. I have placed my UIPickerViewdidSelectRow inside of my prepare for segue function. However the selected strings are not going to my next View Controller. Could someone explain to me what I am doing wrong? I really appreciate it.

import UIKit

class LengthViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {


    @IBOutlet weak var lengthTextField: UITextField!
    @IBOutlet weak var lengthPickerView: UIPickerView!
    var startingUnit = ["","Feet","Inches","Nanometer","Millimeter","Meters","Kilometer","Yards","Miles"]
    var finalUnit  = ["","Feet","Inches","Nanometer","Millimeter","Meters","Kilometer","Yards","Miles"]
    var feet = Double()
    var inches = Double()
    var nanometer = Double()
    var millimeter = Double()
    var meters = Double()
    var kilometer = Double()
    var yards = Double()
    var miles = Double()

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
        view.addGestureRecognizer(tap)
        lengthPickerView.delegate = self
        lengthPickerView.dataSource = self
        lengthTextField.delegate = self

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


        guard let oldText = textField.text, let r = Range(range, in: oldText) else {

            return true
        }

        let newText = oldText.replacingCharacters(in: r, with: string)
        let isNumeric = newText.isEmpty || (Double(newText) != nil)
        let numberOfDots = newText.components(separatedBy: ".").count - 1

        let numberOfDecimalDigits: Int
        if let dotIndex = newText.firstIndex(of: ".") {
            numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
        } else {
            numberOfDecimalDigits = 0
        }

        return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 5
    }
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        var label = UILabel()
        if let v = view as? UILabel { label = v }
        label.font = UIFont (name: "System", size: 20)
        label.textColor = UIColor.white
        label.text =  startingUnit[row]
        label.text = finalUnit[row]
        label.textAlignment = .center
        return label
    }
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return startingUnit.count
        }else{
            return finalUnit.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return startingUnit[row]
        }else{
            return finalUnit[row]
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let lengthOutput = segue.destination as! LengthOutputViewController


    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
           lengthOutput.startingLength = startingUnit[row] //This is where i try to send to next view controller
        }
        if component == 1 {
            lengthOutput.endingLength = finalUnit[row] //This is where i try to send to next view controller
        }
    }

    }

    @IBAction func calculatePressed(_ sender: Any) {
        if lengthTextField == nil {
            createAlert(title: "Missing length value", message: "Enter value")
        }else{
            performSegue(withIdentifier: "lengthOuput", sender: nil)
        }
    }

    func createAlert (title: String, message: String){
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: { (Action) in
            alert.dismiss(animated: true, completion: nil)
        }))
        self.present(alert, animated: true, completion: nil)
    }

}

How to set a UIPickerView selected value from Realm?

$
0
0

I have setup a viewcontroller where there are 7 "questions" and 7 "answers". I've created a UIPickerView that allows users to select their answer when they click on the answer's UITextField, and save it in realm.

However, when a user has already selected an answer (example: "Agree"), "Agree" doesn't show up as the selected row in the UIPickerView when I click the UITextField for that answer.

How do I set the default or "selectedrow" for the UIPickerview to the answer that is displayed in the UITextField and is saved in Realm?

import UIKit
import RealmSwift

class QuestionViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupDelegateForPickerView()
        setupDelegatesForTextFields()
    }

    override func viewWillAppear(_ animated: Bool) {
        loadAnswers()
    }

    @IBOutlet weak var Question1TextField: UITextField!

    @IBOutlet weak var Question2TextField: UITextField!

    @IBOutlet weak var Question3TextField: UITextField!

    @IBOutlet weak var Question4TextField: UITextField!

    @IBOutlet weak var Question5TextField: UITextField!

    @IBOutlet weak var Question6TextField: UITextField!

    @IBOutlet weak var Question7TextField: UITextField!

    // Setting up a UIPickerview from the ToolbarPickerView class

    let realm = try! Realm()

    var answers: Results<Answer>?

    var answerArray = [UITextField]()

    func loadAnswers() {
        var answersGiven = realm.objects(Answer.self).filter("id = 1")
        for answer in answersGiven {
            Question1TextField.text = answer.Answer1
            Question2TextField.text = answer.Answer2
            Question3TextField.text = answer.Answer3
            Question4TextField.text = answer.Answer4
            Question5TextField.text = answer.Answer5
            Question6TextField.text = answer.Answer6
            Question7TextField.text = answer.Answer7
        }
    }

    let pickerView = ToolbarPickerView()

    let Menu = ["Strongly Disagree",
                "Disagree",
                "Neutral",
                "Agree",
                "Strongly Agree"]

    var selectedMenu : String?

    func setupDelegatesForTextFields() {
        //appending textfields in an array
        answerArray += [Question1TextField, Question2TextField, Question3TextField, Question4TextField, Question5TextField, Question6TextField, Question7TextField]
        //using the array to set up the delegates, inputview for pickerview and also the inputAccessoryView for the toolbar
        for answer in answerArray {
            answer.delegate = self
            answer.inputView = pickerView
            answer.inputAccessoryView = pickerView.toolbar
        }
    }

    func setupDelegateForPickerView() {
        pickerView.dataSource = self
        pickerView.delegate = self
        pickerView.toolbarDelegate = self
    }

    func setDefaultValue(item: String, inComponent: Int){
     if let indexPosition = Menu.firstIndex(of: item){
       pickerView.selectRow(indexPosition, inComponent: inComponent, animated: true)
     }
    }

        // Dismissing Keyboard on tapped
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.view.endEditing(true)
        }
    }

extension QuestionViewController : UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.pickerView.reloadAllComponents()
    }
}

extension QuestionViewController : UIPickerViewDelegate, UIPickerViewDataSource {
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.Menu.count
    }

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

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


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

        let answer = Answer()
        answer.id = 1


        // Check if the textfield isFirstResponder.
        if Question1TextField.isFirstResponder {
            Question1TextField.text = self.Menu[row]
            answer.Answer1 = Question1TextField.text

            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer1": self.Menu[row]], update: .modified)
            }
        } else if Question2TextField.isFirstResponder {
            Question2TextField.text = self.Menu[row]
            answer.Answer2 = Question2TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer2": self.Menu[row]], update: .modified)
            }
        } else if Question3TextField.isFirstResponder {
            Question3TextField.text = self.Menu[row]
            answer.Answer3 = Question3TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer3": self.Menu[row]], update: .modified)
            }
        } else if Question4TextField.isFirstResponder {
            Question4TextField.text = self.Menu[row]
            answer.Answer4 = Question4TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer4": self.Menu[row]], update: .modified)
            }
        } else if Question5TextField.isFirstResponder {
            Question5TextField.text = self.Menu[row]
            answer.Answer5 = Question5TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer5": self.Menu[row]], update: .modified)
            }
        } else if Question6TextField.isFirstResponder {
            Question6TextField.text = self.Menu[row]
            answer.Answer6 = Question6TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer6": self.Menu[row]], update: .modified)
            }
        } else if Question7TextField.isFirstResponder {
            Question7TextField.text = self.Menu[row]
            answer.Answer7 = Question7TextField.text
            try! realm.write {
                realm.create(Answer.self, value: ["id": 1, "Answer7": self.Menu[row]], update: .modified)
            }
        } else {
        //log errors
        }
    }
}

extension QuestionViewController: ToolbarPickerViewDelegate {

    func didTapDone() {
      let row = self.pickerView.selectedRow(inComponent: 0)
      self.pickerView.selectRow(row, inComponent: 0, animated: false)
      selectedMenu = self.Menu[row]
        self.view.endEditing(true)
    }

    func didTapCancel() {
       self.view.endEditing(true)
    }
}

Here is the Toolbar Class just incase.


import UIKit

protocol ToolbarPickerViewDelegate: class {
    func didTapDone()
    func didTapCancel()
}

class ToolbarPickerView: UIPickerView {

    public private(set) var toolbar: UIToolbar?
    public weak var toolbarDelegate: ToolbarPickerViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit() {
        let toolBar = UIToolbar()
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneTapped))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelTapped))

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

        toolBar.backgroundColor = UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 0.5)
                    toolBar.tintColor = UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 0.5)
                    UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor(red: 0/255.0, green: 142.0/255.0, blue: 44.0/255.0, alpha: 1.0),
                    NSAttributedString.Key.font: UIFont(name: "Clinton", size: 14)], for: UIControl.State.normal)

        self.toolbar = toolBar
    }

    @objc func doneTapped() {
        self.toolbarDelegate?.didTapDone()
    }

    @objc func cancelTapped() {
        self.toolbarDelegate?.didTapCancel()
    }
}

extension String {
    // formatting text for currency textField
    func currencyFormatting() -> String {
        if let value = Double(self) {
            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
            formatter.maximumFractionDigits = 0
            if let str = formatter.string(for: value) {
                return str
            }
        }
        return ""
    }
}

UIPickerViewDataSource vs UIPickerViewDelegate logic

$
0
0

Why aren't methods like – pickerView:titleForRow:forComponent: part of UIPickerViewDataSource instead of UIPickerViewDelegate as it is currently? After all, the titles are data...

This seems very inconsistent to me. For example, UITableViewDataSource contains both the methods – tableView:cellForRowAtIndexPath: and – tableView:numberOfRowsInSection: which seems logical.

Why then for UIPickerView are the methods giving the number of rows and the methods giving the actual rows separated between UIPickerViewDataSource and UIPickerViewDelegate? Is there some logic to this I've missed?

How to customise UIPickerView height?

$
0
0

How can I customise the height of a UIPickerView? I would like it to be taller more than 250.

I have done the following but I'm unable to set the given height.

-(void)pickerview:(id)sender
{
    pickerView=[[UIPickerView alloc] initWithFrame:CGRectMake(0,200,320,400)];
    pickerView.transform = CGAffineTransformMakeScale(0.75f, 0.75f);
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator = YES;
    pickerView.backgroundColor = [UIColor lightGrayColor];
    [pickerView selectRow:1 inComponent:0 animated:YES];
    [self.view addSubview:pickerView];
    // [contentView addSubview:pickerView];
}

Get selected row in UIPickerView for each component

$
0
0

I have an UIPickerView with 3 components populated with 2 NSMutableArrays (2 components have the same array).

A tutorial says:

//PickerViewController.m
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row);
}

But I want to show the selected row for each component in an UIAlertViewafter the user touched an UIButton.

Is there a way to do this? Or must I just use 3 invisible UILabels as buffer?

Thanks in advance.

Viewing all 593 articles
Browse latest View live


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