How can I pull different items from an array within a class? - swift

I'm creating a quiz application with multiple categories. If the user would like to select a category, they would "turn on" the switch for that category. Then a Bool value will be set to true if the switch is on and false if it is off. This Bool value would then be sent to the next view controller where if it had a true value, a function would run that would add the array of the selected category's question, to an array that holds the arrays of the selected categories.
Currently, this is how my application functions:
I have a swift file called Question, which creates a class for the basic structure of a question. Then I have another file called QuestionBank which holds a class, and within that class is an array of the questions I created using the class within the Question.swift file. From there, in the view controller for my game, I call the class that holds the array of questions and my code then displays each question, with all its options, in the order that they were called in the array. How would I make it so that the users can access specific questions or a specific group of questions within the array based on user input? I already attempted creating multiple arrays of questions and attempting to call those and combine so the user can be tested on both categories, but I am unable to for some reason.
First View Controller:
import UIKit
class ViewControllerTrivia: UIViewController {
var historySelection = Bool()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let gameController = segue.destination as! ViewControllerGame
gameController.isHistorySelected = historySelection
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
#IBAction func swipeToHome(_ sender: Any) {
performSegue(withIdentifier: "triviaToHome", sender: ViewControllerHome.self)}
#IBAction func startGame(_ sender: Any) {
performSegue(withIdentifier: "triviaToGame", sender: ViewControllerGame.self)
}
#IBAction func historySelectionSwitch(_ sender: UISwitch) {
if (sender.isOn == true) {
var historySelection = true
print("on")
} else {
var historySelection = false
print("off")
}
}
}
Second View Controller:
import UIKit
class ViewControllerGame: UIViewController {
var isHistorySelected = Bool()
#IBOutlet weak var questionCounter: UILabel!
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var progressView: UIView!
#IBOutlet weak var questionLabel: UILabel!
//Outlet for Buttons
#IBOutlet weak var optionA: UIButton!
#IBOutlet weak var optionB: UIButton!
#IBOutlet weak var optionC: UIButton!
#IBOutlet weak var optionD: UIButton!
var allQuestions = [(Question(questionText: "History: What does FBLA stand for?", choiceA: "A. Formidable Business Learners of America", choiceB: "B. Future Business Learners of America", choiceC: "C.Future Business Leaders of America", choiceD: "D.Fleeting Business Learners Of America", answer: 3)),]
var historyQuestions = [(Question(questionText: "History: Who was the founder of the FBLA program?", choiceA: "A. Edward D. Miller", choiceB: "B. Conrad N. Hilton", choiceC: "C. Hamden L. Forkner", choiceD: "Elena Daly", answer: 3)) ]
var questionNumber: Int = 0
var score: Int = 0
var selectedAnswer: Int = 0
func questionSelection() {
if isHistorySelected == true{
allQuestions.append(contentsOf: historyQuestions)
}
}
//Making only the top corners of the progress view visible
func roundProgressCorners() {
self.progressView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
override func viewDidLoad() {
super.viewDidLoad()
roundProgressCorners()
questionSelection()
updateQuestion()
updateUI()
// Do any additional setup after loading the view.
}
#IBAction func answerPressed(_ sender: UIButton) {
if sender.tag == selectedAnswer{
print("correct")
score += 1
}else {
print("wrong")
}
questionNumber += 1
updateQuestion()
}
func updateQuestion(){
if questionNumber <= allQuestions.count - 1{
questionLabel.text = allQuestions[questionNumber].question
optionA.setTitle(allQuestions[questionNumber].optionA, for: UIControl.State.normal)
optionB.setTitle(allQuestions[questionNumber].optionB, for: UIControl.State.normal)
optionC.setTitle(allQuestions[questionNumber].optionC, for: UIControl.State.normal)
optionD.setTitle(allQuestions[questionNumber].optionD, for: UIControl.State.normal)
selectedAnswer = allQuestions[questionNumber].correctAnswer
updateUI()
}else {
restartQuiz()
performSegue(withIdentifier: "gameToEndScreen", sender: ViewControllerEndScreen.self)
}
}
func updateUI(){
scoreLabel.text = "Score: \(score)"
questionCounter.text = "\(questionNumber + 1)/\(allQuestions.count)"
progressView.frame.size.width = (view.frame.size.width / CGFloat(allQuestions.count)) * CGFloat(questionNumber + 1)
}
func restartQuiz(){
score = 0
questionNumber = 0
updateQuestion()
}
}
For the final result, I would prefer for the user to be able to select which categories they would like to be quizzed on and then the app will then combine the selected categories.

You would have to re-design your data structure, I though of something as below, may be helpful to you or you can get some more idea.
//1. Create an enum of Question Category
enum QuestionCatgory: String{
case Sports = "Sports"
case Politics = "Politicd"
case Science = "Science"
}
//2. Create a Structure that will hold details about each Question, including its category
struct QuestionsDetail{
let question: String
let options: [String]
let currectOption: Int
let category: QuestionCatgory
init(question: String, options: [String], correctOption: Int, category: QuestionCatgory){
self.question = question
self.options = options
self.currectOption = correctOption
self.category = category
}
}
class ViewController: UIViewController {
var questionList: [QuestionsDetail] = []
override func viewDidLoad() {
super.viewDidLoad()
//3. Create data source of your question. Preferably get this data from backend or store it in a Plist or JSON file for better maintainability. In this example its hardcoded
questionList = createDataSource()
//4. Call this method to get questions specific for a Category. You can use this array to populate the question in a ViewController. Use delegate to capture user response to maintain the scorecard and other things
let questionListOfCategory = getQuestionsList(forCategory: .Science)
print("Questions List for:\n\(questionListOfCategory)\n")
}
func getQuestionsList(forCategory category: QuestionCatgory) -> [QuestionsDetail]{
var questionListOfCategory: [QuestionsDetail] = []
for question in questionList {
if question.category.rawValue == category.rawValue{
questionListOfCategory.append(question)
}
}
return questionListOfCategory
}
func createDataSource() -> [QuestionsDetail]{
let questionDetail1 = QuestionsDetail(question: "Question1", options: ["Option1 A", "Option1 B", "Option1 C", "Option1 D"], correctOption: 2, category: .Sports)
let questionDetail2 = QuestionsDetail(question: "Question2", options: ["Option2 A", "Option2 B", "Option2 C", "Option2 D"], correctOption: 4, category: .Politics)
let questionDetail3 = QuestionsDetail(question: "Question3", options: ["Option3 A", "Option3 B", "Option3 C", "Option3 D"], correctOption: 1, category: .Science)
let questionDetail4 = QuestionsDetail(question: "Question4", options: ["Option4 A", "Option4 B", "Option4 C", "Option4 D"], correctOption: 3, category: .Sports)
let questionDetail5 = QuestionsDetail(question: "Question5", options: ["Option5 A", "Option5 B", "Option5 C", "Option5 D"], correctOption: 4, category: .Politics)
var questionList: [QuestionsDetail] = []
questionList.append(questionDetail1)
questionList.append(questionDetail2)
questionList.append(questionDetail3)
questionList.append(questionDetail4)
questionList.append(questionDetail5)
return questionList
}
}

Related

How to put UILabel and UIImage into the class method

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var chargeLabel: UILabel!
#IBOutlet weak var bigDogLabel: UILabel!
#IBOutlet weak var cafeImageView: UIImageView!
override func viewDidLoad() {
}
struct DogCafe{
var name: String
var charge: Int
var bigDog: Bool
var cafeImage: UIImage
init(name: String, charge: Int, bigDog: Bool, cafeImage: UIImage) {
self.name = name
self.charge = charge
self.cafeImage = cafeImage
self.bigDog = bigDog
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
dogCafe.message()
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
dogCafe2.message()
}
}
func message() {
nameLabel.text = "카페 \(name) 입니다"
chargeLabel.text = "입장료는 \(charge) 입니다"
cafeImageView.image = cafeImage
if bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
Instance member 'nameLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'chargeLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'cafeImageView' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
Instance member 'bigDogLabel' of type 'ViewController' cannot be used on instance of nested type 'ViewController.DogCafe'
you can use like below
#IBAction func ohdodokButton(_ sender: UIButton) {
let dogCafe = DogCafe(name: "카페 오도독", charge: 3500, bigDog: true, cafeImage: #imageLiteral(resourceName: "ohdodok"))
setCurrentDogAttributes(currentDog: dogCafe)
}
#IBAction func meltingButton(_ sender: UIButton) {
let dogCafe2 = DogCafe(name: "멜팅", charge: 5000, bigDog: false, cafeImage: #imageLiteral(resourceName: "melting"))
setCurrentDogAttributes(currentDog: dogCafe)
}
func setCurrentDogAttributes(currentDog:DogCafe){
nameLabel.text=currentDog.name
//Set your Values Here
}
Your approach is wrong. You need to read up on separation of concerns. I'd also suggest reading up on the MVC (Model View Controller) design pattern, which is a pretty common way to do development on iOS.
In your code, DogCafe is a model object. It contains data that you want your app to manipulate and display.
A model object should not know anything about how it is being used. It just holds data.
Your view controller should take the model object and display it to its views. One way to handle that is to add a display(cafe:) method to your view controller:
class ViewController: UIViewController {
// The rest of your view controller variables and functions would go here...
func display(cafe: DogCafe) {
nameLabel.text = "카페 \(cafe.name) 입니다"
chargeLabel.text = "입장료는 \(cafe.charge) 입니다"
cafeImageView.image = cafe.cafeImage
if cafe.bigDog == true {
bigDogLabel.text = "대형견 출입이 가능한 매장입니다"
} else {
bigDogLabel.text = "대형견 출입이 불가능한 매장입니다"
}
}
}

array of image literals getting "Type of expression is ambiguous without more context" in swift 5

I am new to coding and am trying to learn Swift. I am making a simple "Rock Paper Scissors" app to practice using MVC.
I have an array (let imagesArray = [image literal, image literal, image literal]
when I have images array in the controller it works fine but when I try to move it to the model I get a "Type of expression is ambiguous without more context" error. Are image arrays not allowed in the model? my understanding is that data should be kept in the model so that's why I am trying to put it in there.
any thoughts would be much appreciated :)
struct GameBrain {
let images = [ #imageLiteral(resourceName: "rock"), #imageLiteral(resourceName: "paper"), #imageLiteral(resourceName: "scissors")]
func playGame() -> Int {
let choices = [0,1,2]
let choice = choices.randomElement()
return choice!
}
mutating func getWinner(choice: Int?) {
}
}
class ViewController: UIViewController {
var gameBrain = GameBrain()
#IBOutlet weak var imageViewLeft: UIImageView!
#IBOutlet weak var imageViewRight: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func goButton(_ sender: UIButton) {
imageViewLeft.image = images[gameBrain.playGame()]
imageViewRight.image = images[gameBrain.playGame()]
}
}
If you move images into the model you have to adjust the references
#IBAction func goButton(_ sender: UIButton) {
imageViewLeft.image = gameBrain.images[gameBrain.playGame()]
imageViewRight.image = gameBrain.images[gameBrain.playGame()]
}
Apparently the index is not needed so this is simpler
var playGame : UIImage {
return images.randomElement()!
}
and
#IBAction func goButton(_ sender: UIButton) {
imageViewLeft.image = gameBrain.playGame
imageViewRight.image = gameBrain.playGame
}

Add or subtract numbers from different viewports in Swift4

I am new here and would like to ask a question that has been working for me for days. I'm just learning Swift 4 and I've come quite a long way. I really do not know what to do any more, and my books on swift do not help me either.
I have created a small testapp, in which should simply be charged.
There are 5 view controllers. The first one has 4 buttons to get to one of the other 4 and to enter a number there in a text box. This number is then output in the first viewcontroller in a label. The numbers are displayed and even the last entered number is displayed again after a restart of the app.
But now I want to charge off the numbers in the first viewcontroller. How can I fix the code?
My Viewports:
my viewports
code from main viewport:
import UIKit
class ViewController: UIViewController, sendValue1, sendValue2, sendValue3, sendValue4 {
#IBOutlet weak var value1: UILabel!
#IBOutlet weak var value2: UILabel!
#IBOutlet weak var value3: UILabel!
#IBOutlet weak var value4: UILabel!
#IBOutlet weak var calculatedValue1: UILabel! // here i want to see the calculated value like from the label 1-4...value1 + value2 + value3 + value4 = ???
#IBOutlet weak var calculatedValue2: UILabel! // here the same like in claculatedValue1 value but with "-" or "*" or something else...
func value1Data(data: String) {
value1.text = data
UserDefaults.standard.set(value1.text, forKey: "value1")
}
func value2Data(data: String) {
value2.text = data
UserDefaults.standard.set(value2.text, forKey: "value2")
}
func value3Data(data: String) {
value3.text = data
UserDefaults.standard.set(value3.text, forKey: "value3")
}
func value4Data(data: String) {
value4.text = data
UserDefaults.standard.set(value4.text, forKey: "value4")
}
override func viewDidAppear(_ animated: Bool) {
if let lastValue1Data = UserDefaults.standard.object(forKey: "value1") as? String {
value1.text = lastValue1Data
}
if let lastValue2Data = UserDefaults.standard.object(forKey: "value2") as? String {
value2.text = lastValue2Data
}
if let lastValue3Data = UserDefaults.standard.object(forKey: "value3") as? String {
value3.text = lastValue3Data
}
if let LastValue4Data = UserDefaults.standard.object(forKey: "value4") as? String {
value4.text = LastValue4Data
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "VC1" {
let SendingVC1: Value1ViewController = segue.destination as! Value1ViewController
SendingVC1.delegate = self
}
if segue.identifier == "VC2" {
let SendingVC2: Value2ViewController = segue.destination as! Value2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "VC3" {
let SendingVC3: Value3ViewController = segue.destination as! Value3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "VC4" {
let SendingVC4: Value4ViewController = segue.destination as! Value4ViewController
SendingVC4.delegate = self
}
}
#IBAction func unwindToView1(_ segue: UIStoryboardSegue) {
}
and the code from one of the other four:
import UIKit
protocol sendValue1 {
func value1Data(data: String)
}
class Value1ViewController: UIViewController {
var delegate: sendValue1? = nil
#IBOutlet weak var textValue1: UITextField!
#IBAction func done(_ sender: Any) {
if delegate != nil {
if textValue1.text != nil {
let data = textValue1.text
delegate?.value1Data(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
why is the result always nil here?
let a = Float(value3.text!) ?? 0
let b = Float(value4.text!) ?? 0
let SUM = a + b
calculatedValue1.text = "\(SUM)" + "m"
No matter what I do, the numbers are not processed ...

How to pass data backwards to a view controller after passing forward?

Im developing a quiz app and there is a second view controller that appears after the initial view controller where you are asked to answer a question. On the second view controller you the user must press a button to return to the initial view controller to be asked another question. However when I segue back from the second view controller I believe a new instance of the initial view controller is being created and the user is asked questions they have already answered. The code in the swift file for my initial view controller is constructed that when once a user is asked a question once that question is removed from an array by it's index. How could I make it to where a new instance of the initial view controller isn't created from segueing from the second view controller? Or is there a way the second view controller can access the same methods as the initial view controller?
Here is my code for the initial view controller:
import UIKit
class ViewController: UIViewController {
var questionList = [String]()
func updateCounter() {
counter -= 1
questionTimer.text = String(counter)
if counter == 0 {
timer.invalidate()
wrongSeg()
counter = 15
}
}
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
questionTimer.text = String(counter)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "incorrectSeg", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "correctSeg", sender: self)
}
//variables
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
#IBOutlet weak var questionLabel: UILabel!
//Answer Button
#IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox))
{
rightSeg()
print ("Correct!")
}
if counter != 0 {
counter = 15
questionTimer.text = String(counter)
}
else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
randomQuestion()
}
override func viewDidAppear(_ animated: Bool)
{
randomQuestion()
}
//variables
var counter = 15
var timer = Timer()
#IBOutlet weak var questionTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
}
Here's the code to the second view controller:
import UIKit
class ContinueScreen: UIViewController {
//correct answer label
#IBOutlet weak var correctLbl: UILabel!
//background photo
#IBOutlet weak var backgroundImage: UIImageView!
func backToQuiz() {
if let nav = self.navigationController {
nav.popViewController(animated: true)
}
else {
self.dismiss(animated: true, completion: nil)
}
}
#IBAction func `continue`(_ sender: Any) {
backToQuiz()
}
What you need, sir is a delegate or an unwind segue. I far prefer delegates because they're easier to understand and I think a bit more powerful.
In your ContinueScreen view controller define a protocol similar to this:
protocol QuizCompletedDelegate {
func completedQuiz()
func canceledQuiz()
}
Also in your ContinueScreen view controller you need to declare an optional delegate of type QuizCompletedDelegate
var delegate: QuizCompletedDelegate?
... and use that delegate to call the functions when appropriate:
#IBAction func didPressContinue(_ sender: Any) {
if allQuestionsAnswered == true {
delegate.completedQuiz()
} else {
delegate.cancelledQuiz()
}
}
In your initial view controller is where you implement the functions for the protocol:
extension ViewController: QuizCompletedDelegate {
func completedQuiz() {
//Handle quiz complete
}
func cancelledQuiz() {
//Handle quiz cancelled
}
}
Then the last thing you need to do is set the delegate of your ContinueScreen view controller in the prepareForSegue function of your initial view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showContinueScreen" {
let continueVC = segue.destination as! ContinueScreen
continueVC.delegate = self
}
}
Remove the call to randomQuestion() on your initial view controller's ViewDidAppear, and you're in business!
It shouldn't create a new View Controller when you go back. If it does - it's very bad - and you should re-architect the flow of your app... To pass data forward, we should use Dependency Injection. To pass data to the previous view controller - use the iOS Delegation Pattern. I recommend to spend 30-40 mins to read (and understand this article), and it will make things more clear for you in the future: http://matteomanferdini.com/how-ios-view-controllers-communicate-with-each-other/.

How to set up a NSComboBox using prepare for segue or init?

I am really struggling to pass the contents of one array from a view controller to another to set up the contents of a nscombobox. I have tried everything I can think of, prepare for segue, init; but nothing seems to work.
the program flow is as follows: the user enter a number into a text field and based on it an array with the size of the number is created. Once the user presses a button the next VC appears that has a combo box and inside that combo box those numbers need to appear. All my attempts result in an empty array being passed. Could someone please take a bit of time and help me out. Im sure I'm doing a silly mistake but cannot figure out what.
Code listing below:
Class that take the user input. At this stage I'm trying to pass the contents of the array in the next class as I gave up on prepare for segue because that one crashes because of nil error. Please note that prepare for segue is uncommented in the code listing just for formatting purposes here. Im my program it is commented out as I am using perform segue at the moment.
Any solution would be nice please. Thank you.
import Cocoa
class SetNumberOfFloorsVC: NSViewController {
//MARK: - Properties
#IBOutlet internal weak var declaredNumber: NSTextField!
internal var declaredFloorsArray = [String]()
private var floorValue: Int {
get {
return Int(declaredNumber.stringValue)!
}
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction private func setNumberOfFloors(_ sender: NSButton) {
if declaredNumber.stringValue.isEmpty {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please specify the number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else if floorValue == 0 || floorValue < 0 {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please input a correct number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else {
for i in 0...floorValue - 1 {
declaredFloorsArray.append(String(i))
}
print("\(declaredFloorsArray)")
let declareNumberOfRoomsVC = SetNumberOfRoomsForFloorVC(boxData: declaredFloorsArray)
declareNumberOfRoomsVC.boxData = declaredFloorsArray
performSegue(withIdentifier: "set number of rooms", sender: self)
}
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.identifier == "set number of rooms" {
if let addRoomsVC = segue.destinationController as? SetNumberOfRoomsForFloorVC {
addRoomsVC.floorBox.addItems(withObjectValues: declaredFloorsArray)
}
}
}
}
this is the class for the next VC with the combo box:
import Cocoa
class SetNumberOfRoomsForFloorVC: NSViewController, NSComboBoxDelegate, NSComboBoxDataSource {
//MARK: - Properties
#IBOutlet internal weak var floorBox: NSComboBox!
#IBOutlet private weak var numberOfRoomsTxtField: NSTextField!
internal var boxData = [String]()
//MARK: - Init
convenience init(boxData: [String]) {
self.init()
self.boxData = boxData
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
floorBox.usesDataSource = true
floorBox.dataSource = self
floorBox.delegate = self
print("\(boxData)")
}
#IBAction private func setRoomsForFloor(_ sender: NSButton) {
}
//MARK: - Delegates
func numberOfItems(in comboBox: NSComboBox) -> Int {
return boxData.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return boxData[index]
}
}
First you should remove the following code.
let declareNumberOfRoomsVC = SetNumberOfRoomsForFloorVC(boxData: declaredFloorsArray)
declareNumberOfRoomsVC.boxData = declaredFloorsArray
I assume you think that the viewController you created here is passed to prepareForSegue. However the storyboard instantiates a new viewController for you.
After that you need to set your declaredFloorsArray as the the boxData of the new viewController in prepareForSegue and you should be good to go.