Force unwrapping nil optional for UIImageView when transitioning to view controller - swift

I'm running into an error when transitioning to view controllers by overriding the built-in prepare() function in Swift. I have a UIImageView for backgrounds on my screens. Here is the code for two of the view controllers in question.
import UIKit
import FirebaseAuth
class HomeVC: UIViewController {
#IBOutlet weak var signOutButton: UIButton!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendsNavButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var profileNavButton: UIButton!
#IBOutlet weak var bumpButton: UIButton!
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var doNotDisturbLabel: UILabel!
#IBOutlet weak var doNotDisturbButton: UIButton!
var userName = ""
var dndIsOn: Bool = false
#IBAction func dndToggled(_ sender: Any) {
dndIsOn = !dndIsOn
User.current.available = !dndIsOn
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).updateData([Constants.Firestore.Keys.available : !dndIsOn])
if dndIsOn {
print("DND is on!")
setupDNDUI()
} else if !dndIsOn {
print("DND is off!")
setupActiveUI()
}
}
#IBAction func signOutTapped(_ sender: Any) {
let firAuth = Auth.auth()
do {
try firAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
print("Successfully signed out")
}
#IBAction func bumpTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toCall, sender: self)
}
#IBAction func friendsNavTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toFriends, sender: self)
}
#IBAction func profileNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(ProfileVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
doNotDisturbLabel.isHidden = true
if !userName.isEmpty {
welcomeLabel.text = "Welcome Back, " + userName + "!"
} else {
welcomeLabel.text = ""
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let friendsVC = segue.destination as? FriendsVC else {
return
}
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).getDocument { (snapshot, err) in
if let err = err {
print(err.localizedDescription)
} else {
let data = snapshot!.data()!
let requests = data[Constants.Firestore.Keys.requests] as? [String]
if let requests = requests {
friendsVC.requests = requests
}
}
}
}
class FriendsVC: UIViewController {
//var friends: [Friend] = User.current.friends
var friends: [User] = []
var requests: [String]?
#IBOutlet weak var requestsNumberLabel: UILabel!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendRequestsButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var friendsTitle: UILabel!
#IBOutlet weak var friendTableView: UITableView!
#IBOutlet weak var addFriendButton: UIButton!
#IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
#IBAction func friendRequestsTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toRequests, sender: self)
}
#IBAction func homeNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(HomeVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
friendTableView.backgroundView?.backgroundColor = .white
friendsTitle.isHidden = false
UserService.getUserArray(uids: User.current.friendUids, completion: { (users) in
guard let users = users else {
print("User has no friends")
return
}
self.friends = users
self.friendTableView.reloadData()
})
guard let requests = self.requests else {
friendRequestsButton.isHidden = true
requestsNumberLabel.isHidden = true
self.tableViewTopConstraint.constant = 0
return
}
requestsNumberLabel.text = requests.count.description
// Do any additional setup after loading the view.
friendTableView.delegate = self
friendTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let homeVC = segue.destination as? HomeVC {
homeVC.userName = User.current.firstName
} else if let requestsVC = segue.destination as? RequestsVC {
UserService.getUserArray(uids: self.requests!) { (requesters) in
if let requesters = requesters {
requestsVC.requesters = requesters
}
}
}
}
}
When my app loads into the home screen, there is no problem, and when a button is tapped to transition to FriendsVC, there is no problem. However, when I try to initiate the transition from HomeVC to ProfileVC or from FriendVC to HomeVC, I get the error: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" at the self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill lines in my viewDidLoad methods. These segues have something in common in that these are the ones where I override the prepare() function, but I'm not sure what I'm doing wrong

Related

Sigbart error during prepare for segue/unwind segue

I have an app where it is a marketplace and when you click on a product, it opens a detail view controller passing the data to display on the DetailVC. Additionally, inside the DetailVC, if you click on a button to claim the product, it segues to another VC to finalize the transaction.
In the DetailVC, there is a back button which is an unwind segue back to the main marketplace VC. Inside the TransactionVC, there is a cancel button which takes you back to the DetailVC.
When I am clicking the backButton in the DetailVC to take me back to the main market VC but I am getting a SIGBART Error and this :
020-07-15 09:05:23.707490-0500 evolutionatx[707:141952] Could not cast value of type 'evolutionatx.MarketplaceViewController' (0x1032c7868) to 'evolutionatx.PopUpPurchaseViewController' (0x1032c7ba8).
Here is the code for the DetailVC
import UIKit
import iCarousel
import CoreData
class MarketDetailViewController: UIViewController, UIScrollViewDelegate, iCarouselDelegate, iCarouselDataSource {
var productImageArray = [UIImage]()
var productVideo = String()
var pointsToPurchase = String()
var productName = String()
var productDescription = String()
var companyLogo = UIImage()
var companyWebsite = String()
var additionalProductImage = [UIImage]()
var companyName = String()
var promoCODE = String()
var buyLink = String()
var slides:[Slide] = [];
//IB
#IBOutlet weak var productNameLabel: UILabel!
#IBOutlet weak var productPriceLabel: UILabel!
#IBOutlet weak var productDescLabel: UILabel!
#IBOutlet weak var claimButton: UIButton!
#IBOutlet weak var imgScrollView: UIScrollView!
#IBOutlet weak var websiteButton: UIButton!
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var logoDisplay: UIImageView!
#IBOutlet weak var carouselView: iCarousel!
#IBOutlet weak var otherProductslabe: UILabel!
var carouselImages = [UIImage]()
var evoCoin = Int()
override func awakeFromNib() {
super.awakeFromNib()
carouselImages = productImageArray
}
override func viewDidLoad() {
super.viewDidLoad()
valueSetter()
imgScrollView.delegate = self
slides = createSlides()
setupSlideScrollView(slides: slides)
pageControl.numberOfPages = slides.count
pageControl.currentPage = 0
view.bringSubviewToFront(pageControl)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
pageControl.currentPage = Int(pageIndex)
let maximumHorizontalOffset: CGFloat = scrollView.contentSize.width - scrollView.frame.width
let currentHorizontalOffset: CGFloat = scrollView.contentOffset.x
// vertical
let maximumVerticalOffset: CGFloat = scrollView.contentSize.height - scrollView.frame.height
let currentVerticalOffset: CGFloat = scrollView.contentOffset.y
let percentageHorizontalOffset: CGFloat = currentHorizontalOffset / maximumHorizontalOffset
let percentageVerticalOffset: CGFloat = currentVerticalOffset / maximumVerticalOffset
}
#IBAction func claimProduct(_ sender: Any) {
print("tap rec")
claimProductandPurchase()
}
func claimProductandPurchase(){
evoCOiner()
if(evoCoin >= Int(pointsToPurchase)!){
print("Transaction Successful")
performSegue(withIdentifier: "proceedQuestion", sender: self)
}
else{
showToast(controller: self, message: "Insufficient EvoCoins", seconds: 0.5)
}
}
func showToast(controller: UIViewController, message : String, seconds: Double) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.view.backgroundColor = UIColor.black
alert.view.alpha = 0.6
alert.view.layer.cornerRadius = 15
controller.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds) {
alert.dismiss(animated: true)
}
}
func evoCoiner(){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "EvoCoins")
request.returnsObjectsAsFaults = false
do{
let result = try context.fetch(request)
for data in result as! [NSManagedObject]
{
evoCoin = data.value(forKey: "evoCoins") as! Int
}
}catch{
print("Failed")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailController = segue.destination as! PopUpPurchaseViewController
detailController.ppromo = promoCODE
detailController.link = buyLink
detailController.coinToPurchase = Int(pointsToPurchase)!
}
//This is the unwind used by the transaction back button
#IBAction func unwindToItem(segue: UIStoryboardSegue) {
}
}
Here is the code in the transaction VC
import UIKit
import AMTabView
import CoreData
class MarketplaceViewController: UIViewController, TabItem {
#IBOutlet weak var sView: UIView!
#IBOutlet weak var evoCoinLabe: UILabel!
//For the sake of simplicity I only kept the Unwind functions
//MARK: - UNWIND FUNCTIONS
#IBAction func unwindToMainMarketView(segue: UIStoryboardSegue) {
}
}
How can I fix this error?
Please advise if my question was not clear or properly phrased (if so, sorry I am pretty new to all of this)
As #matt already said in his comment and the error clearly states, you cannot cast a MarketplaceViewController to a PopUpPurchaseViewController.
Furthermore instead of doing a forced cast, always look for a safe one like below. Doing so will prevent crashes.
if let detailController = segue.destination as? PopUpPurchaseViewController {
...
}
else {
// log failed to cast
}

Swift: Why can I pass info from one IBAction to another, but not to a function

I am trying to get the values for splitValue and tipPercent into the getSettings() at the bottom. Why can I get the values for both of those in the IBAction calculatePressed, but when I try to get the values into the function the value is nil. I am sooo confused. Thank you for the help!
#IBOutlet weak var billTextField: UITextField!
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBOutlet weak var splitNumberLabel: UILabel!
var tipChosen = ""
var totalPerPerson = ""
var tipPercent = ""
var splitValue = ""
#IBAction func tipChanged(_ sender: UIButton) {
tipPercent = sender.currentTitle!
if sender.isSelected == true {
return
}
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
if sender.currentTitle == "0%" {
tipChosen = "0.00"
} else if sender.currentTitle == "10%" {
tipChosen = "0.10"
} else if sender.currentTitle == "20%" {
tipChosen = "0.20"
}
billTextField.endEditing(true)
}
#IBAction func stepperValueChanged(_ sender: UIStepper) {
splitValue = String(Int(sender.value))
splitNumberLabel.text = String(Int(sender.value))
}
#IBAction func calculatePressed(_ sender: UIButton) {
let bill = Float(billTextField.text!)!
let tip = Float(tipChosen)!
let tax = bill * tip
let splitNumber = Float(splitNumberLabel.text!)
let total = (bill + tax) / Float(splitNumber!)
totalPerPerson = "$\(String(format: "%.2f", total))"
performSegue(withIdentifier: "goToTotal", sender: self)
}
func getSettings() -> String {
return "Split between \(splitValue) people, with a \(tipPercent) tip."
}
Ok, sorry it took me a bit, but I finally think I understand what I did.
class CalculatorViewController: UIViewController {
var tip = 0.0
var finalBill = ""
var split = 2
#IBOutlet weak var billTextField: UITextField!
#IBOutlet weak var zeroPctButton: UIButton!
#IBOutlet weak var tenPctButton: UIButton!
#IBOutlet weak var twentyPctButton: UIButton!
#IBOutlet weak var splitNumberLabel: UILabel!
#IBAction func tipChanged(_ sender: UIButton) {
if sender.isSelected == false {
sender.isSelected = false
} else if sender.isSelected == true {
sender.isSelected = true
}
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
sender.isSelected = true
billTextField.endEditing(true)
}
#IBAction func stepperValueChanged(_ sender: UIStepper) {
splitNumberLabel.text = Int(sender.value).description
}
#IBAction func calculatePressed(_ sender: UIButton) {
if zeroPctButton.isSelected == true {
tip = 0.0
} else if tenPctButton.isSelected == true {
tip = 0.1
} else if twentyPctButton.isSelected == true {
tip = 0.2
}
print(tip)
let bill = Double(billTextField.text!)
split = Int(Double(splitNumberLabel.text!)!)
if billTextField.text != "" {
let billWithTip = (bill! * tip) + bill!
let billWithTipSplit = billWithTip / Double(split)
finalBill = String(format: "%.2f", billWithTipSplit)
print(billWithTip)
}
self.performSegue(withIdentifier: "getResults", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "getResults" {
let destinationVC = segue.destination as! ResultsViewController
destinationVC.finalBill = finalBill
destinationVC.split = split
destinationVC.tip = tip
}
}
}
class ResultsViewController: UIViewController {
#IBOutlet weak var totalLabel: UILabel!
#IBOutlet weak var settingsLabel: UILabel!
var tip = 0.0
var split = 2
var finalBill = ""
override func viewDidLoad() {
super.viewDidLoad()
totalLabel.text = "$\(finalBill)"
settingsLabel.text = "Split between \(Int(split)) people, with a \(Int(tip * 100))% tip"
}
#IBAction func recalculatePressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
I did what you suggested with the string and some minor calculations on the second view controller, changed the values of a few declared properties and got rid of the getSettings(). I was under the impression that I couldn't pass data without a return value from a function. Thank you for the help!

How to fix 'Swift Protocols/Delegates setting UIImages - Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value'?

I am letting the user choose a background image upon sign in. Base on user choice of image selection, I want to show another view controller with the image that the user selected. I follow some examples from youtube but I am getting 'Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value' and the image is not set.
protocol SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage)
}
class SelectBackgroundViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var snowBackgroundImage: UIImageView!
#IBOutlet weak var desertBackgroundImage: UIImageView!
#IBOutlet weak var pathwayBackgroundImage: UIImageView!
#IBOutlet weak var beachBackgroundImage: UIImageView!
// MARK: Properties
var imageSelectionDelegate: SelectionImageDelegate!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.imageSelectionDelegate = FootprintViewController()
setButtonCorners()
}
override func viewWillAppear(_ animated: Bool) {
snowBackgroundImage.center.x -= view.bounds.width
desertBackgroundImage.center.x -= view.bounds.width
pathwayBackgroundImage.center.x -= view.bounds.width
beachBackgroundImage.center.x -= view.bounds.width
}
#IBAction func didTappedSnowBackground(_ sender: Any) {
print("tapped snow")
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Snow_Background")!)
print("set image")
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedDesertBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Desert_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedPathwayBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Pathway_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
#IBAction func didTappedBeachBackground(_ sender: Any) {
imageSelectionDelegate.setBackgroundImage(selectedImage: UIImage(named: "Beach_Background")!)
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
}
class FootprintViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var emptyFootprintImageView: UIImageView!
// MARK: Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FootprintViewController: SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage) {
backgroundImageView.image = selectedImage
}
}
class FootprintViewController: UIViewController {
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var emptyFootprintImageView: UIImageView!
// MARK: Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FootprintViewController: SelectionImageDelegate {
func setBackgroundImage(selectedImage: UIImage) {
backgroundImageView.image = selectedImage
}
}
Please try to set optinal imageSelectionDelegate in SelectBackgroundViewController like this;
var imageSelectionDelegate: SelectionImageDelegate?
"implicitly unwrapping" means that you are trying to access an "implicitly unwrapped optional" value, which does not hold a value but is nil.
In your case, you are dealing with two optionals:
The delegate imageSelectionDelegate might not be set.
UIImage(named: "Snow_Background") might return nil
Accessing the delegate - if nil would result in the Unexpectedly found nil while implicitly unwrapping an Optional value error, while accessing the image - if nil - would result in Unexpectedly found nil while unwrapping an Optional value
So, since you observe the first error, the delegate is nil, which seems strange because you set it in viewDidLoad.
To investigate a little more, you could add some more trace information to your action handler, to check what happens:
#IBAction func didTappedSnowBackground(_ sender: Any) {
print("tapped snow")
guard imageSelectionDelegate != nil else {
print ("delegate is not set")
return
}
guard let bgImage = UIImage(named: "Snow_Background") else {
print ("Snow_Background image does not exist")
return
}
imageSelectionDelegate.setBackgroundImage(selectedImage: bgImage)
print("set image")
let vc = (self.storyboard?.instantiateViewController(withIdentifier: "FootprintVC"))!
self.presentViewController(vc)
}
Then check the output.

swift read write to firestore documents and collections

from the IOS app i'm trying to update with new data 5 different "collection" in Firestore. I'm able to do that but to 1 collection only. I can't figure it out how to push the updates to all 5 collections at once. Any help is greatly appreciated.
import UIKit
import Firebase
class itemDataViewController: UIViewController {
#IBOutlet var itemLabels: [UILabel]!
#IBOutlet weak var testLabel: UILabel!
#IBOutlet weak var firstItemField: UITextField!
#IBOutlet weak var secondItemField: UITextField!
#IBOutlet weak var thirdItemField: UITextField!
#IBOutlet weak var fourthItemField: UITextField!
#IBOutlet weak var fithItemField: UITextView!
var docRef: DocumentReference!
var infoListener: ListenerRegistration!
#IBAction func updateData(_ sender: Any) {
guard let firstItemText = firstItemField.text, !firstItemText.isEmpty else { return }
guard let secondItemText = secondItemField.text, !secondItemText.isEmpty else { return }
guard let thirdItemText = thirdItemField.text, !thirdItemText.isEmpty else { return }
guard let fourthItemText = fourthItemField.text, !fourthItemText.isEmpty else { return }
guard let fithItemText = fithItemField.text, !fithItemText.isEmpty else { return }
let dataToSave: [String: Any] = ["firstItem": firstItemText]
docRef.setData(dataToSave) { (error) in
if let error = error {
print("Oh no! Could not save: \(error.localizedDescription)")
} else {
print("Data Saved")
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
infoListener = docRef.addSnapshotListener { (docSnapshot, error) in
guard let docSnapshot = docSnapshot, docSnapshot.exists else { return }
let myData = docSnapshot.data()
let firstItemUpdate = myData?["firstItem"] as? String ?? ""
self.firstItemField.text = "\(firstItemUpdate)"
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
infoListener.remove()
}
override func viewDidLoad() {
super.viewDidLoad()
docRef = Firestore.firestore().document("2/firstItem")
(itemLabels as NSArray).setValue(10, forKey: "cornerRadius")
// Do any additional setup after loading the view.
}
}

Text field is permanently in the second view controller upon segue

I have been working on an app that allows multiple text fields from the first view controller pass over to the second view controller upon pressing a button. However, the text fields are permanently in the second view controller when I only want them to be if the button is pressed. Here is the code for the first view controller! Any help is greatly appreciated.
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var textField1: UITextField!
#IBAction func buttonTwo(_ sender: Any) {
if textField1.text != "" {
performSegue(withIdentifier: "segue", sender: self)
}
}
#IBAction func buttonOne(_ sender: Any) {
if textField.text != "" {
performSegue(withIdentifier: "segue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var secondController = segue.destination as! SecondViewController
secondController.myString1 = textField1.text!
secondController.myString = textField.text!
}
}
Here is the code in the second view controller:
class SecondViewController: UIViewController {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var label1: UILabel!
var myString = String()
var myString1 = String()
override func viewDidLoad() {
super.viewDidLoad()
label.text = myString
label1.text = myString1
// Do any additional setup after loading the view.
}
}
Image of storyboard
This happens because, prepare for segue will be called every time you perform some segue action.
You should manage to have a bool variable that helps you track, if any button is clicked or not, if the segue is performed from the click of the button, then only you will have to set the text while preparing for segue.
here is your updated viewController
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var textField1: UITextField!
var isButtonClicked: Bool = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
/*reset isButtonClicked to false, when you back from second viewController */
isButtonClicked = false
}
#IBAction func buttonTwo(_ sender: Any) {
if textField1.text != "" {
isButtonClicked = true
performSegue(withIdentifier: "segue", sender: self)
}
}
#IBAction func buttonOne(_ sender: Any) {
if textField.text != "" {
isButtonClicked = true
performSegue(withIdentifier: "segue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if isButtonClicked {
var secondController = segue.destination as! SecondViewController
secondController.myString1 = textField1.text!
secondController.myString = textField.text!
}
}
}
Try and share your results.