How selectRow of PickerView can affect on Button enabled? - swift

I have UIPickerView and button. I want if I choose raw number 0 then button is not enabled and vice versa. I have this construction in my code:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
...
#IBOutlet weak var buttonOutlet: UIButton!
#IBOutlet weak var firstPicker: UIPickerView!
#IBOutlet weak var secondPicker: UIPickerView!
let firstData = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
let secondData = ["00", "10", "20", "30", "40", "50"]
#IBOutlet weak var firstLabel: UILabel!
#IBOutlet weak var secondLabel: UILabel!
var first: Int!
var second: Int!
var firstRaw = 1
var secondRaw = 0
...
override func viewDidLoad() {
super.viewDidLoad()
self.firstPicker.delegate = self
self.firstPicker.dataSource = self
self.secondPicker.delegate = self
self.secondPicker.dataSource = self
firstPicker.selectRow(firstRaw, inComponent: 0, animated: true)
secondPicker.selectRow(firstRaw, inComponent: 0, animated: true)
if (self.firstRaw == 0) && (self.secondRaw == 0) {
self.buttonOutlet.isEnabled = false
} else {
self.buttonOutlet.isEnabled = true
}
...
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == firstPicker {
...
} else {
...
}
Why this construction doesn't work?

To detect when a value is selected you must implement the UIPickerViewDelegate, also implement didSelectRow method of picker view. I'm assuming that you already populate your picker view data.
class ViewController : UIViewController, UIPickerViewDelegate {
#IBOutlet weak var buttonOutlet: UIButton!
#IBOutlet weak var firstPicker: UIPickerView!
var firstRaw = 1
...
override func viewDidLoad() {
super.viewDidLoad()
self.firstPicker.delegate = self
...
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
if self.firstRaw == 0 {
self.buttonOutlet.isEnabled = false
} else {
self.buttonOutlet.isEnabled = true
}
}
}

Related

How to add elements to a realm database

I am working on a simple app that catalogues information. Right now I am just trying to collect information and then add it to a realm database. Unfortunately I cannot figure it out and no matter what method I try (based on tutorials and the Realm website) I get the error "Use of unresolved identifier 'realm'.
This is the code based on the command button executing the command.
#IBAction func Submit(_ sender: Any) {
let myList = WineList()
myList.vinyard = Vinyard.text
myList.type = typeField.text
myList.name = Name.text
myList.grape = Grape.text
myList.year = Year.text
myList.price = Price.text
myList.rating = rateField.text
myList.purchased = purch
myList.notes = Notes.text
//from realm website example
try! realm.write{
realm.add(myList)
}
//from tutorials
//realm.beginWrite()
//realm.add(myList)
//try realm.commitWrite()
}
Can anyone please advise me on what I am doing wrong? I will post all of my code below.
import UIKit
import RealmSwift
class RankViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var purch = ""
#IBOutlet weak var typeField : UITextField!
#IBOutlet weak var rateField : UITextField!
#IBOutlet weak var Vinyard: UITextField!
#IBOutlet weak var Name: UITextField!
#IBOutlet weak var Grape: UITextField!
#IBOutlet weak var Year: UITextField!
#IBOutlet weak var Price: UITextField!
#IBOutlet weak var Notes: UITextField!
#IBAction func Purchased(_ sender: UISwitch) {
if (sender.isOn == true){
purch = "Yes"
}
else {
purch = "No"
}
}
let wineTypes = ["Red","White","Rose","Sparkling","Ice - Red","Ice - White", "Port","Fruit","Other"]
let wineRate = ["Hurray", "Meh", "Boo"]
var typeView = UIPickerView()
var rateView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
print (Realm.Configuration.defaultConfiguration.fileURL)
typeView.delegate = self
typeView.dataSource = self
rateView.delegate = self
rateView.dataSource = self
Vinyard.delegate = self
Name.delegate = self
Grape.delegate = self
Year.delegate = self
Price.delegate = self
Notes.delegate = self
typeField.inputView = typeView
rateField.inputView = rateView
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView == typeView {
// Returns for typeView
return 1
}
else if pickerView == rateView {
// Returns for rateView
return 1
}
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == typeView {
// Returns for typeView
return wineTypes.count
}
else if pickerView == rateView {
// Returns for rateView
return wineRate.count
}
return wineRate.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == typeView {
// Returns for typeView
return wineTypes[row]
}
else if pickerView == rateView {
// Returns for rateView
return wineRate[row]
}
return wineRate[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == typeView {
// Do stuff for typeView
typeField.text = wineTypes[row]
typeField.resignFirstResponder()
}
else if pickerView == rateView {
// Do stuff for rateView
typeField.text = wineRate[row]
typeField.resignFirstResponder()
}
}
#IBAction func Submit(_ sender: Any) {
let myList = WineList()
myList.vinyard = Vinyard.text
myList.type = typeField.text
myList.name = Name.text
myList.grape = Grape.text
myList.year = Year.text
myList.price = Price.text
myList.rating = rateField.text
myList.purchased = purch
myList.notes = Notes.text
//from realm website example
try! realm.write{
realm.add(myList)
}
//from tutorials
//realm.beginWrite()
//realm.add(myList)
//try realm.commitWrite()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
Year.resignFirstResponder()
Price.resignFirstResponder()
}
}
extension RankViewController : UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
Separate file
import Foundation
import RealmSwift
class WineList: Object {
#objc dynamic var vinyard: String?
#objc dynamic var name: String?
#objc dynamic var grape: String?
#objc dynamic var year: String?
#objc dynamic var price: String?
#objc dynamic var notes: String?
#objc dynamic var type: String?
#objc dynamic var rating: String?
#objc dynamic var purchased: String?
}
Variables only exist with the function or class they are created. So take these two functions
func getData() {
let realm = Realm()
let results = realm.objects...
}
and
func printData() {
print(results) //this won't work
}
as you can see, the var 'realm' is instantiated in getData so that var is only available within that function and would not be available within the printData function.
In your case you've instantiated the realm var within viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
therefore it will only be available within the viewDidLoad function.
To correct your issue, you need to instantiate realm within the function where you're trying to use it
#IBAction func Submit(_ sender: Any) {
let myList = WineList()
...
let realm = try! Realm()
try! realm.write{
realm.add(myList)
}
to expand on that a bit. Take your RankViewController class
class RankViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var purch = ""
See the 'purch' var? That's called a 'class var' and because it's defined at a high level within the class, it would be available throughout the class.
func printData() {
print(self.purch) //this will work
}
note that I preceded purch with self. when I referenced it. To me, that's a good indicator it's a class var and makes the code more readable. However, it's not required.

How to use one pickerview for multiple textfield?

I am trying to build something (I am new to Xcode and swift) where I can choose a meal for a day from an array with Picker View, and I want my choice to display in that specific day's textfield. I have got this working, but for 1 day only. How can I get this same function working for all (7) days?
I managed to get the picker view when click on next textfield as well (Tuesday), but as I choose from the list the Mondays textfield will follow what I am doing for Tuesday. They are mirrored. I do get that I should probably make something to get thatTuesday-Picker unique somehow, but that's where Im stuck. I don't know what to change/write. Anyone with any ideas? I have googled around and find a lot regarding picker views but nothing for how they can been used in this specific way...
//
// ViewController.swift
// dropdown
//
// Created by -- on 2019-08-26.
// Copyright © 2019 --. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var monday: UITextField!
#IBOutlet weak var tuesday: UITextField!
#IBOutlet weak var wednesday: UITextField!
#IBOutlet weak var thursday: UITextField!
#IBOutlet weak var friday: UITextField!
#IBOutlet weak var saturday: UITextField!
#IBOutlet weak var sunday: UITextField!
// the menu
let Menu = ["Palak Paner",
"Spagetti Köttfärssås",
"Thai Haloumi",
"Thai Quorn",
"Linssoppa",
"SparrisPasta",
"Gröt",
"Gulasch"]
let tuesdayMenu = ["Palak Paner",
"Spagetti Köttfärssås",
"Thai Haloumi",
"Thai Quorn",
"Linssoppa",
"SparrisPasta",
"Gröt",
"Gulasch"]
//When a menu from the list is selected, it will be shown as a string
var mondaySelectedMenu: String?
var tuesdaySelectedMenu: String?
override func viewDidLoad() {
super.viewDidLoad()
//Call on these functions when loaded
createMondayMenuPicker()
createTuesdayMenuPicker()
createToolbar()
}
// This is the pickerView
func createMondayMenuPicker() {
let mondayMenuPicker = UIPickerView()
mondayMenuPicker.delegate = self
monday.inputView = mondayMenuPicker
}
func createTuesdayMenuPicker() {
let tuesdayMenuPicker = UIPickerView()
tuesdayMenuPicker.delegate = self
tuesday.inputView = tuesdayMenuPicker
}
// This is the "DONE" button
func createToolbar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "DONE", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
monday.inputAccessoryView = toolBar
tuesday.inputAccessoryView = toolBar
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
// This is the details for the pickerView
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Menu.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Menu[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
mondaySelectedMenu = Menu[row]
tuesdaySelectedMenu = tuesdayMenu[row]
monday.text = mondaySelectedMenu
tuesday.text = tuesdaySelectedMenu
}
}
So, I want to call on that same array when click on all seven days but I want to display the unique choices for everyday chosen from that list. Any ideas? Thanks a lot!
One way to achieve this is to do using the below approach. I have separated out toolbar functionality into its own class.
Create a new class pickerview's toolbar (in this case i have called ToolbarPickerView.swift)
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.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = .black
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
self.toolbar = toolBar
}
#objc func doneTapped() {
self.toolbarDelegate?.didTapDone()
}
#objc func cancelTapped() {
self.toolbarDelegate?.didTapCancel()
}
}
In ViewController
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var monday: UITextField!
#IBOutlet weak var tuesday: UITextField!
#IBOutlet weak var wednesday: UITextField!
#IBOutlet weak var thursday: UITextField!
#IBOutlet weak var friday: UITextField!
#IBOutlet weak var saturday: UITextField!
#IBOutlet weak var sunday: UITextField!
var daysArray = [UITextField]()
let pickerView = ToolbarPickerView()
let Menu = ["Palak Paner",
"Spagetti Köttfärssås",
"Thai Haloumi",
"Thai Quorn",
"Linssoppa",
"SparrisPasta",
"Gröt",
"Gulasch"]
var selectedMenu : String?
override func viewDidLoad() {
super.viewDidLoad()
setupDelegateForPickerView()
setupDelegatesForTextFields()
}
func setupDelegatesForTextFields() {
//appending textfields in an array
daysArray += [monday, tuesday, wednesday, thursday, friday, saturday, sunday]
//using the array to set up the delegates, inputview for pickerview and also the inputAccessoryView for the toolbar
for day in daysArray {
day.delegate = self
day.inputView = pickerView
day.inputAccessoryView = pickerView.toolbar
}
}
func setupDelegateForPickerView() {
pickerView.dataSource = self
pickerView.delegate = self
pickerView.toolbarDelegate = self
}
}
Create an extension for textfield delegate
extension ViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickerView.reloadAllComponents()
}
}
Extension for pickerview and toolbar
extension ViewController : 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) {
// Check if the textfield isFirstResponder.
if monday.isFirstResponder {
monday.text = self.Menu[row]
} else if tuesday.isFirstResponder {
tuesday.text = self.Menu[row]
} else if wednesday.isFirstResponder {
wednesday.text = self.Menu[row]
} else if thursday.isFirstResponder {
thursday.text = self.Menu[row]
} else if friday.isFirstResponder {
friday.text = self.Menu[row]
} else if saturday.isFirstResponder {
saturday.text = self.Menu[row]
} else if sunday.isFirstResponder {
sunday.text = self.Menu[row]
} else {
//log errors
}
}
}
extension ViewController: 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)
}
}
PickerView's didSelectRow function can be simplified by changing it to below
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
for day in daysArray {
if day.isFirstResponder {
day.text = self.Menu[row]
}
}
}
Hopefully this answer will help you.
Create a common picker class like below:
class PKMultiPicker: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource {
internal typealias PickerDone = (_ firstValue: String, _ secondValue: String) -> Void
private var doneBlock : PickerDone!
private var firstValueArray : [String]?
private var secondValueArray = [String]()
static var noOfComponent = 2
class func openMultiPickerIn(_ textField: UITextField? , firstComponentArray: [String], secondComponentArray: [String], firstComponent: String?, secondComponent: String?, titles: [String]?, toolBarTint: UIColor = UIColor.black, doneBlock: #escaping PickerDone) {
let picker = PKMultiPicker()
picker.doneBlock = doneBlock
picker.openPickerInTextField(textField, firstComponentArray: firstComponentArray, secondComponentArray: secondComponentArray, firstComponent: firstComponent, secondComponent: secondComponent, toolBarTint: toolBarTint)
if titles != nil {
let label = UILabel(frame: CGRect(x: UIScreen.main.bounds.size.width/4 - 10, y: 0, width: 100, height: 30))
label.text = titles![0].uppercased()
label.font = UIFont.boldSystemFont(ofSize: 18)
picker.addSubview(label)
if PKMultiPicker.noOfComponent > 1 {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
label.text = titles![1].uppercased()
label.font = UIFont.boldSystemFont(ofSize: 18)
picker.addSubview(label)
} else {
label.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 30)
label.textAlignment = NSTextAlignment.center
}
}
}
private func openPickerInTextField(_ textField: UITextField?, firstComponentArray: [String], secondComponentArray: [String], firstComponent: String?, secondComponent: String?, toolBarTint: UIColor = UIColor.black) {
firstValueArray = firstComponentArray
secondValueArray = secondComponentArray
self.delegate = self
self.dataSource = self
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(pickerCancelButtonTapped))
cancelButton.tintColor = toolBarTint
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(pickerDoneButtonTapped))
doneButton.tintColor = toolBarTint
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action:nil)
let toolbar = UIToolbar()
toolbar.sizeToFit()
let array = [cancelButton, spaceButton, doneButton]
toolbar.setItems(array, animated: true)
toolbar.backgroundColor = UIColor.lightText
textField?.inputView = self
textField?.inputAccessoryView = toolbar
let index = self.firstValueArray?.index(where: {$0.lowercased() == (firstComponent ?? "").lowercased() })
self.selectRow(index ?? 0, inComponent: 0, animated: true)
if PKMultiPicker.noOfComponent > 1 {
let index1 = self.secondValueArray.index(where: {$0.lowercased() == (secondComponent ?? "").lowercased() })
self.selectRow(index1 ?? 0, inComponent: 1, animated: true)
}
}
#IBAction private func pickerCancelButtonTapped(){
UIApplication.shared.keyWindow?.endEditing(true)
}
#IBAction private func pickerDoneButtonTapped(){
UIApplication.shared.keyWindow?.endEditing(true)
let index1 : Int?
let firstValue : String?
index1 = self.selectedRow(inComponent: 0)
if firstValueArray?.count == 0{return}
else{firstValue = firstValueArray?[index1!]}
var index2 :Int!
var secondValue: String!
if PKMultiPicker.noOfComponent > 1 {
index2 = self.selectedRow(inComponent: 1)
secondValue = secondValueArray[index2]
}
self.doneBlock((firstValue ?? ""), (secondValue ?? ""))
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return firstValueArray!.count
}
return secondValueArray.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return PKMultiPicker.noOfComponent
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0:
return firstValueArray?[row]
case 1:
return secondValueArray[row]
default:
return ""
}
}
}
Example Code to open picker and manage selection, there are some more options, you can manage number of components also:-
PKMultiPicker.noOfComponent = 1
PKMultiPicker.openMultiPickerIn(textField, firstComponentArray: ["Apple", "Mango","Grapes","Pine apple"], secondComponentArray: [], firstComponent: textField.text, secondComponent: nil, titles: nil, toolBarTint: AppColors.themeGreen) { (firstSelect, secondSelect) in
print("first select : \(firstSelect)")
textField.text = firstSelect // you can set text here to the respective text field.
}
Here #pawan_kumar has described a way for using same picker view for multiple textfields with same data. but you can bind different data sources for that as well. https://stackoverflow.com/a/60631018/10505343 has a sample code for that. here I use UITextField.isFirstResponder to decide what data should be loaded to the picker view. Hope this answer also will be helpful for you.

Can't save data from UIPickerView

I tried to program a sign up view controller and use a UIPickerView for country choice. The issue is that when I tried to pass the picker country to Parse to save the input, Xcode give me an error. Why Xcode can't allow me to use the selected data to Parse? The error is in the last line.
Any help guys?
#IBOutlet var usernameTextField: UITextField!
#IBOutlet var fullnameTextField: UITextField!
#IBOutlet var emailTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
#IBOutlet var phonenumberTextField: UITextField!
#IBOutlet var countryPicker: UIPickerView!
let countryData: [String] = ["Saudi Arabia", "Turkey"]
#available(iOS 2.0, *)
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countryData.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let countrySelect = countryData[row]
print(countrySelect)
}
override func viewDidLoad() {
super.viewDidLoad()
countryPicker.dataSource = self
countryPicker.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signUpAction(sender: AnyObject) {
// Declare user object
let newUser = PFUser()
let fullName = fullnameTextField.text!
let username = usernameTextField.text!
let email:String = emailTextField.text!
let password:String = passwordTextField.text!
let phoneNumber:Int? = Int(phonenumberTextField.text!)
// Passing arguments
newUser.username = username
newUser["fullName"] = fullName
newUser.email = email
newUser.password = password
newUser["phoneNumber"] = phoneNumber! as Int
newUser["country"] = countryData [row]
Based on your comment that the error is "unresolved identifier row":
You are never declaring a variable named row, yet you're using it. You can either replace the use of this undefined variable with the correct array index that will give you the country from the countryData variable OR you make sure that row is actually declared and accessible in your function.

ScrollView, TextField and pickerview trouble

My problem is that when I run the project and click the first textfield ( the others are empty for now ) the app crashes with this error :
Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<UICompatibilityInputViewController: 0x12dd4c600> should have parent view controller:<Sai_Service.ServiceAppointment: 0x12dd151a0> but requested parent is:<UIInputWindowController: 0x12e00b600>'.
This is my code:
import UIKit
class ServiceAppointment: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var ScrollView: UIScrollView!
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var StateField: UITextField!
#IBOutlet weak var CityField: UITextField!
#IBOutlet weak var VehRegNumberField: UITextField!
#IBOutlet weak var LocationField: UITextField!
#IBOutlet weak var CurrentKmsField: UITextField!
#IBOutlet weak var apptDateFIeld: UITextField!
#IBOutlet weak var apptTypeField: UITextField!
#IBOutlet weak var pickupField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
ScrollView.contentSize.height = 1000
pickerView.hidden = true;
StateField.text = States[0]
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
self.StateField.inputView = pickerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var States = ["Italy","United States","UK","France"]
//MARK: - Delegates and data sources
//MARK: Data Sources
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return States.count
}
//MARK: Delegates
func pickerView2(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return States[row]
}
func pickerView3(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
StateField.text = States[row]
pickerView.hidden = true;
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
pickerView.hidden = false
return false
}
}
I think it's a problem of multiple view, so I wrote in the viewDidLoad:
self.StateField.removeFromSuperView()
but then all the ScrollViews disappeared obviously.
How I can make this work so that when I press the textfield, the pickerview appears?

segue to another view controller

I've been trying to segue some labels across to another view controller but i can't seem to work it out.
my first view controller:
import UIKit
class firstViewController: UIViewController,UITextFieldDelegate {
#IBOutlet weak var label1: UILabel!
#IBOutlet weak var label2: UILabel!
#IBOutlet weak var label3: UILabel!
#IBOutlet weak var label4: UILabel!
#IBOutlet weak var label5: UILabel!
#IBOutlet weak var label6: UILabel!
var pickerLabels: [String!] {
return [label1.text,label2.text,label3.text,label4.text,label5.text,label6.text]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as thirdViewController
controller.vc2Labels = pickerLabels //pickerLabels shows error
}
}
the labels in here are what I'm trying to segue but "pickerLabels" keeps coming up with an error
my second view controller:
import UIKit
class secondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var vc2Labels: [String]!
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component:Int) -> Int{
return vc2Labels.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{
return vc2Labels[row]
}
I think I know your problem. You seem to be passing in an array of String into a string object.
Maybe you can alter your second view controller's variable to be:
var vc2Labels: [String]!
but I wouldn't recommend using implicit unwrapping of optional, since it allows a passing in of nil. You can declare an empty array like this.
var vc2Labels = [String]()
Hope this helps. More context would be helpful.