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

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.

Related

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
}

my UIswitch value is nil even when its on I have to turn swich off and then back on for it to set value

using UIswitch to set value
my variable is static because im using them in diffrent swift file
so when I run program and click registration button it prints nil
even tho its on (button stays the way it was left when closing app)
I have to toggle it and then click registration button for it to print optional(true)
what can i do so user dont have to togggle everytime they open app or when it shows on when app opened but value is nil
also I just want it to print true/false (how do i unwrap)
class FirstViewController: UIViewController, UITextFieldDelegate {
static var FirstColor: Bool!
#IBAction func home(_ sender: RoundButton) {
}
#IBAction func Registration(_ sender: RoundButton) {
print(FirstViewController.FirstColor)
}
#IBAction func ColorSwitch(_ sender: UISwitch) {
if sender.isOn{
FirstViewController.FirstColor = true
}else{FirstViewController.FirstColor = false }
}
}
If you want to persist the switch status you need to store it in UserDefaults. Don't add a static property in FirstViewController. Create a separate class like this with a computed property
class Color {
static var firstColor: Bool {
get { return UserDefaults.standard.bool(forKey: "firstColor") }
set { UserDefaults.standard.set(newValue, forKey: "firstColor") }
}
}
In FirstViewController's viewDidLoad get last status and update
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.isOn = Color.firstColor
}
In Switch's action change it
#IBAction func ColorSwitch(_ sender: UISwitch) {
sender.isOn = !sender.isOn
Color.firstColor = sender.isOn
}
You could try to use the value of the isOn property directly. Does this help? Also I suggest that you use better names for your handlers.
class FirstViewController: UIViewController, UITextFieldDelegate
{
static var FirstColor: Bool!
#IBAction func registrationTapped(_ sender: RoundButton)
{
print(FirstViewController.FirstColor)
}
#IBAction func colorChanged(_ sender: UISwitch)
{
FirstViewController.FirstColor = sender.isOn
}
}

VIPER architecture using Swift to store data in presenter

So I'm setting up a simple VIPER architecture in Swift.
The Interactor gets some data from an API, and passes the data to the presenter that then passes formatted data to the view.
The presenter will process the data, and just count the number of objects that are downloaded. To do so I have stored a var in the presenter. The question is should I store data in the presenter?
Interactor:
class Interactor {
weak var presenter: Presenter?
func getData() {
ClosureDataManager.shared.fetchBreaches(withURLString: baseUrl + breachesExtensionURL, completion: { [weak self] result in
guard let self = self else { return }
switch result {
case .failure(let error):
print(error)
case .success(let breaches):
self.presenter?.dataDidFetch(breaches: breaches)
self.presenter?.dataNumberDidFetch(number: breaches.count)
}
})
}
}
Presenter:
class Presenter {
var wireframe: Wireframe?
var view: ViewController?
var interactor: Interactor?
var dataDownloaded = 0
func viewDidLoad() {
print ("presenter vdl")
}
func loadData() {
interactor?.getData()
}
func dataDidFetch(breaches: [BreachModel]) {
view?.dataReady()
}
func showDetail(with text: String, from view: UIViewController) {
wireframe?.pushToDetail(with: text, from: view)
}
func dataNumberDidFetch(number: Int) {
dataDownloaded += number
view?.showData(number: String(dataDownloaded) )
}
}
View (ViewController)
protocol dataViewProtocol {
func showData(number: String)
}
class ViewController: UIViewController, dataViewProtocol {
#IBOutlet weak var showDetailButton: UIButton!
#IBOutlet weak var dataLabel: UILabel!
// weak here means it won't work
var presenter: Presenter?
#IBAction func buttonPressAction(_ sender: UIButton) {
presenter?.loadData()
}
#IBAction func buttonShowDetailAction(_ sender: UIButton) {
presenter?.showDetail(with: "AAA", from: self)
}
func dataReady() {
showDetailButton.isEnabled = true
}
func showData(number: String) {
dataLabel.text = number
}
override func viewDidLoad() {
super.viewDidLoad()
Wireframe.createViewModule(view: self)
presenter?.viewDidLoad()
}
}
Router (Wireframe)
class Wireframe {
static func createViewModule (view: ViewController) {
let presenterInst = Presenter()
view.presenter = presenterInst
view.presenter?.wireframe = Wireframe()
view.presenter?.view = view
view.presenter?.interactor = Interactor()
view.presenter?.interactor?.presenter = presenterInst
}
}
So should the presenter be used to store the number of objects downloaded?
What have you tried I've implemented the var, as shown above. This is a minimum example of the problem.
What resources have you used I've looked on StackOverflow, and Googled the issue. I can't find an answer, but know I could store the data in the view but I think this is incorrect. I could store the number of data in the Interactor, but this also doesn't seem right. It all seems...to violate separation of concerns...
I won't do your homework / use a different architecture / You should use protocols / Why is there a single protocol in your implementation This isn't homework, it is for my own self - study. There may be other architectures that can be used to do this (and coding to protocols is good practice) but this is about storing a variable in the presenter. I want to know if I should store the variable in the presenter, using VIPER and using Swift. Comments about trivia around the question are seldom helpful if they are about variable names, or the like.
What is the question? I want to know if I can store the number of downloaded data items in the presenter.

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 know which NSCombobox selector calling the Delegate

I have the following code written in SWIFT for OS X App, the code is working fine (NSComboBox are select able only, not editable)
I have these two IBOutlet projNewProjType and projNewRouter, when I change the the selection of either of the NSComboBox, I can see the correct selected Index value and String value but how to check that the returned Index value is from projNewProjType NOT projNewRouter in the comboBoxSelectionDidChange()
import Cocoa
class NewProjectSetup: NSViewController, NSComboBoxDelegate {
let comboxProjValue: [String] = [“No”,”Yes”]
let comboxRouterValue: [String] = ["No","Yes"]
#IBOutlet weak var projNewProjType: NSComboBox!
#IBOutlet weak var projNewRouter: NSComboBox!
#IBAction func btnAddNewProject(sender: AnyObject) {
print(“Add New Button Pressed!”)
}
#IBAction func btnCancel(sender: AnyObject) {
self.dismissViewController(self)
}
override func viewDidLoad() {
super.viewDidLoad()
addComboxValue(comboxProjValue,projNewProjType)
addComboxValue(comboxRouterValue,projNewRouter)
self.projNewProjType.selectItemAtIndex(0)
self.projNewRouter.selectItemAtIndex(0)
self.projNewProjType.delegate = self
self.projNewRouter.delegate = self
}
func comboBoxSelectionDidChange(notification: NSNotification) {
let comboBox: NSComboBox = (notification.object as? NSComboBox)!
print("comboBox comboBox: \(comboBox)")
/* This printed “<NSComboBox: 0x6000001e1a00>”*/
print("comboBox objectValueOfSelectedItem: \(comboBox.objectValueOfSelectedItem)")
/* This printed the correct selected String value */
print("comboBox indexOfSelectedItem: \(comboBox.indexOfSelectedItem)")
/* This printed the correct selected Index value */
}
/* Add value to Combo box */
func addComboxValue(myVal:[String],myObj:AnyObject){
let myValno: Int = myVal.count
for i in 0..<myValno{
myObj.addItemWithObjectValue(myVal[i])
}
}
}
You already know the addresses of your two NSComboBox outlets and you know the address of which NSComboBox caused that notification to trigger, so why not do something like:
func comboBoxSelectionDidChange(notification: NSNotification) {
let comboBox: NSComboBox = (notification.object as? NSComboBox)!
if comboBox == self.projNewProjType
{
print("selection changed via self.projNewProjType")
}
if comboBox == self.projNewRouter
{
print("selection changed via self.projNewRouter")
}
You can set identifiers to your NSComboBoxes in IB. Select your combo box and choose identity inspector and name identifier. Then you are able to do like this:
if comboBox.identifier == "someIdentifier" {
// Do something
}