A
A
Aleksandr Govorukhin2017-05-16 11:19:59
iOS
Aleksandr Govorukhin, 2017-05-16 11:19:59

How to set up 1 PickerView to 2 UITextFiled Swift 3?

Hello! There is 1 picker and 2 UITextField, when choosing a value in one of the TextFields, it is duplicated simultaneously in the other. How can I change the code so that these cells can select different values? Thanks in advance for your time.
158cccee1e6245c0b2560e5a3b6c8a19.png

//
//  AddNewShipTableViewController.swift
//  GreenWorld
//
//  Created by Aleksandr Govorukhin on 08.05.17.
//  Copyright © 2017 Aleksandr Govorukhin. All rights reserved.
//

import UIKit
import CoreData

class AddNewShipTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
    
    @IBAction func backToAddNewShip(segue: UIStoryboardSegue) {
        
    }
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var nameShip: UITextField!
    @IBOutlet weak var organization: UITextField!
    @IBOutlet weak var inspectionDate: UITextField!
    @IBOutlet weak var deadweight: UITextField!
    @IBOutlet weak var grossTonnage: UITextField!
    @IBOutlet weak var diesel: UITextField!
    @IBOutlet weak var contractYear: UITextField!
    @IBOutlet weak var constructionYear: UITextField!
    @IBOutlet weak var deliveryDate: UITextField!
    
    var answerYears = ["1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020"]
    
    
    var reportNOx: String!
    var reportSOx: String!
    var reportCO2: String!
    var reportBallastWater: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Получение сегодняшней даты в String
        let date = NSDate() // Get Todays Date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        let stringDate: String = dateFormatter.string(from: date as Date)
        inspectionDate.text = stringDate
        
        //Установка делегата на текстовое поле
        constructionYear.delegate = self
        contractYear.delegate = self
        
        //Добавление кнопки Done
        let pickerView = UIPickerView()
        pickerView.delegate = self
        contractYear.inputView = pickerView
        constructionYear.inputView = pickerView
        
        
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height/6, width: self.view.frame.size.width, height: 40.0))
        
        toolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
        
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(AddNewShipTableViewController.donePressed))
        
        let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil)
        
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width / 3, height: self.view.frame.size.height))
        
        let textBtn = UIBarButtonItem(customView: label)
        
        toolBar.setItems([flexSpace,textBtn,flexSpace,doneButton], animated: true)
        
        constructionYear.inputAccessoryView = toolBar
        contractYear.inputAccessoryView = toolBar
        nameShip.inputAccessoryView = toolBar
        organization.inputAccessoryView = toolBar
        inspectionDate.inputAccessoryView = toolBar
        deadweight.inputAccessoryView = toolBar
        grossTonnage.inputAccessoryView = toolBar
        
        //Скрываем клавиатуру
//        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AddNewShipTableViewController.dismissKeyboard))
//        
//        view.addGestureRecognizer(tap)

    }
    
    //Добавление кнопки Done 
    func donePressed(_ sender: UIBarButtonItem) {
        
        constructionYear.resignFirstResponder()
        contractYear.resignFirstResponder()
        nameShip.resignFirstResponder()
        organization.resignFirstResponder()
        inspectionDate.resignFirstResponder()
        deadweight.resignFirstResponder()
        grossTonnage.resignFirstResponder()
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return answerYears.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        return answerYears[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        contractYear.text = answerYears[row]
        constructionYear.text = answerYears[row]
    }


    //Функция скрытия клавиатуры
    func dismissKeyboard() {
        view.endEditing(true)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    //Добавление действия на 1 ячейку
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                let imagePicker = UIImagePickerController()
                imagePicker.delegate = self
                imagePicker.allowsEditing = false
                imagePicker.sourceType = .photoLibrary
                
                self.present(imagePicker, animated: true, completion: nil)
            }
        }
        
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //Запоминаем выбранное изображение
        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        dismiss(animated: true, completion: nil)
    }
    
    //Добавление кнопки Done
    func doneButtonAction()
    {
        view.endEditing(true)
    }


        
    //Реализация кнопки "Сохранить"
    @IBAction func saveNewShip() {
        
        //Проверка заполненность всех полей
        var error = ""
        if (nameShip.text?.isEmpty)! {
            error = "'Название судна'"
        } else if (organization.text?.isEmpty)! {
            error = "'Организация'"
        } else if (deadweight.text?.isEmpty)! {
            error = "'Дедвейт'"
        } else if (grossTonnage.text?.isEmpty)! {
            error = "'Гросс-тонаж'"
        } else if (diesel.text?.isEmpty)! {
            error = "'Дизель'"
        } else if (contractYear.text?.isEmpty)! {
            error = "'Дата контракта'"
        } else if (constructionYear.text?.isEmpty)! {
            error = "'Дата постройки'"
        } else if (deliveryDate.text?.isEmpty)! {
            error = "'Навигация'"
        }
        
        if error != "" {
            let alertController = UIAlertController(title: "Ошибка", message: "Сохранение не удалость, потому что поле \(error) не заполненно", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Хорошо", style: .default, handler: nil)
            
            alertController.addAction(okAction)
            
            self.present(alertController, animated: true, completion: nil)
            
            return
        }
        
        //Реализация рассчета дипломной работы
        //Расчет NOx
    
        
        if Int(constructionYear.text!)! > 2000 && Int(constructionYear.text!)! < 2010 {
            reportNOx = "NOx требуется 1 Уровень"
        } else if Int(constructionYear.text!)! > 2011 {
            reportNOx = "NOx требуется 2 Уровень"
        } else if Int(constructionYear.text!)! < 2000 {
            reportNOx = "Нет требований NOx"
        }
        
        //Расчет SOx
        reportSOx = "IMO: 0.1% S ограничение на все зоны контроля выбросов (ECA)\n0.5% S ограничение во всем мире с 2020\nEU: 0.1% S ограничение во всех портах\nChina:Тяньцзин/Далянь/Море Бохай; Гонконг/Гуанчжоу; и Шанхай: 0.5% S ограничение в основных портах с 2017; во всех портах с 2018; и на всей территории с 2019"
        
        reportCO2 = "Требуется план управления энергопотреблением судна (SEEMP). Требуется расчетный индекс эффективности энергопотребления (EEDI)."
        
        //Расчет Ballast Water
        reportBallastWater = "IMO: Система очистки балластных вод требует от IOPP (Международный протокол от загрязнения нефтью) продление срока до 2022/05/15\nUS: Очистка балластной воды требуется из первого планового докования, после 2016.01.01 (Если продление предоставлено береговой охраной США) "
        
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let ship = Ship(context: context) // Link Task & Context
        ship.image = UIImagePNGRepresentation(imageView.image!)! as NSData
        ship.nameShip = nameShip.text!
        ship.organization = organization.text!
        ship.inspectionDate = inspectionDate.text!
        ship.reportNOx = reportNOx
        ship.reportSOx = reportSOx
        ship.reportBallastWater = reportBallastWater
        ship.reportCO2 = reportCO2
        
        
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
        
        performSegue(withIdentifier: "myUnwindAction", sender: self)

    }
    
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
ManWithBear, 2017-05-16
@SnapSh0t

You assign the same picker to two different fields. Make two different pickers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question