How to use functions from other swift files (same target) in same project - swift

Hey I have 2 Classes each in own swift file. Im basically doing this only to get a better overview in my Viewcontroller. Still, I need to get access to the data or call the func from other files in my view controller.swift file. Its in the same Target so I don't need to import it in my view controller file right?
If I do override the func viewDidLoad() I get an Exception so I guess I am only allowed to do it once (-> in my viewController.swift)
//ViewController.swift
class ViewController: UIViewController{
#IBOutlet weak var xMotion: UILabel!
#IBOutlet weak var yMotion: UILabel!
#IBOutlet weak var zMotion: UILabel!
#IBOutlet weak var lineChartView: LineChartView!
#IBOutlet weak var lineChartView2: LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
timebuffer.append(Double(ts1))
colors.append(UIColor.red)
Graphen.customizeChart(values: buffer1.map { Double($0) })
Graphen.filteredChart(values: buffer2.map { Double($0) })
Graphen.multipleCharts()
}
//Graphen.swift
class Graphen : ViewController
{
//creates Plot with specific numbers/data
func customizeChart(values: [Double]){
var dataEntries: [ChartDataEntry] = []
for i in 0..<buffer1.count{//dataPoints.count
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry) }
lineChartDataSet = LineChartDataSet(entries: dataEntries, label: nil)
lineChartDataSet.circleRadius = 0.5
let lineChartData = LineChartData(dataSet: lineChartDataSet)
self.lineChartView.data = lineChartData
}
}

viewDidLoad() is a lifecycle method of a UIViewController's instance. Thus, it can be overridden in each UIViewCiontroller subclass, i.e.
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
//your code here...
}
}
class Graphen : ViewController
{
override func viewDidLoad() {
super.viewDidLoad()
//your code here...
}
}
Now, you don't need to import any file/class as long as they are in the same target.
Now, since Graphen's customizeChart(values:) method is an instance method, so you need to create an instance of Graphen first and then use it to call its instance methods like so,
let graphen = Graphen()
graphen.customizeChart(values: buffer1.map { Double($0) })
Similarly call other instance methods of Graphen. Assuming that filteredChart(values:) and multipleCharts() are also instance methods, you can invoke them like,
graphen.filteredChart(values: buffer2.map { Double($0) })
graphen.multipleCharts()

Related

Using Delegation to Pass Data from the Initial View Controller to a Second View Controller - Swift

I am trying to understand delegation in Swift better, and I have seen how delegation can be used to pass data from a second view controller back to an initial view controller. But I am confused about how to pass data from the initial view to a second view using delegation. I have initialized an instance of the delegate in my initial view and implement the delegate protocol in the second view, but I am still unsuccessful in passing the data from initial view to second view using delegation. Any advice on what I might be doing wrong would be appreciated! Here is the storyboard view of what my delegation attempt looks like. 1
Initial View Class:
import UIKit
class ViewController: UIViewController {
var data: DataDelegate?
#IBOutlet weak var text: UITextField!
#IBOutlet weak var send: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func send(_ sender: Any) {
let msg = text.text!
data?.sendData(data: msg)
print("SENDING MESSAGE: \(msg)")
}
}
protocol DataDelegate {
func sendData(data: String)
}
Second View Class:
import UIKit
class RVC: UIViewController, DataDelegate {
#IBOutlet weak var delegationLabel: UILabel!
#IBOutlet weak var message: UILabel!
#IBOutlet weak var back: UIButton!
let vc = ViewController()
func sendData(data: String) {
print("DATA SENT")
let msg = data
print(msg)
message.text = data
}
override func viewDidLoad() {
super.viewDidLoad()
print("LOADED")
vc.data = self
// Do any additional setup after loading the view.
}
}

OS X Hello World Swift tutorial

So I'm following this tutorial for Swift and am not getting the desired result at the end. This is my code for the ViewController:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var nameField: NSTextField!
#IBOutlet weak var helloLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func sayButtonClicked(_ sender: Any) {
var name = nameField.stringValue
if name.isEmpty {
name = "World"
}
let greeting = "Hello \(name)!"
helloLabel.stringValue = greeting
}
}
And the following is the result:
When I debug the program however it does show the correct variables:
What am I doing wrong here?
Turns out I didn't stretch out the the Label field enough.

Having issues passing a delegate from NSWindowController subclass to my ViewController

I'm having issues with passing a custom protocol (MainWindowControllerProtocol) to the EditorViewController from the MainWindowController, which is subclass of NSWindowController. Please help.
EditorViewController.swift
extension EditorViewController: MainWindowControllerProtocol {
func didOpenFile() {
print("TODO: Open File") // never called, but it should be
}
}
class EditorViewController: NSViewController {
// - IBOutlets
#IBOutlet weak var treeOutlineView: NSOutlineView!
#IBOutlet var codeTextView: NSTextView!
#IBOutlet weak var counterTextField: NSTextField!
#IBOutlet weak var languageTextField: NSTextField!
//public var editor = Editor()
//var rootNode: Node?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
//rootNode = Path(Path.userDownloads).node
// Issue is here
if let windowController = NSApplication.shared.mainWindow?.windowController as? MainWindowController {
windowController.delegate = self
}
else {
print("Doesnt work") // prints this
}
//treeOutlineView.reloadData()
}
}
MainWindowController
public protocol MainWindowControllerProtocol {
func didOpenFile()
}
class MainWindowController: NSWindowController {
var delegate: MainWindowControllerProtocol?
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
#IBAction func openFile(_ sender: Any) {
print("In here") // this is called?
delegate?.didOpenFile() // but this never is apparently
}
}
Maybe this topic should help.
This method might return nil if the application’s nib file hasn’t
finished loading, if the receiver is not active, or if the application
is hidden.
Have you checked if NSApplication.shared.mainWindow is nil or just NSApplication.shared.mainWindow?.windowController cannot be casted to your controller class ?

Swift: set #IBOutlet static

I want change #IBOutlet text value from another class
How i can set #IBOutlet to static ?
Below code not work:
#IBOutlet internal static var boxGender: UIView!
You can set a static value of your controller and get all values from them. But this is not a right way to reach your outlets. You should pass your controller to other class instance.
class Test: UIViewController {
var boxGender: UIView!
static var instance: Test?
override func viewDidLoad() {
super.viewDidLoad()
Test.instance = self
}
}
Test.instance?.boxGender
An IBOutlet cannot be static. (The compiler will give the error Only instance properties can be declared #IBOutlet)
class SomeViewWithALabel: UIView {
#IBOutlet weak var myLabel: UILabel!
// ... methods and properties
}
class MyController: UIViewController {
#IBOutlet weak var someViewWithALabel: SomeViewWithALabel!
//...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
someViewWithALabel?.myLabel.text == "Custom text"
}
}

Delegate Method is not called in Swift?

I want to pass a Bool value from on view controller to another without the help of segues. So i referred & got Delegates.
I have applied delegates in my App. But the Delegate method is not being called. I don't know where i am making the mistake.
So Please help me.
MainViewController
class MainViewController: UIViewController, WriteValueBackDelegate {
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
Second View Controller
class LoginController: UIViewController {
#IBOutlet weak var LoginLabel: UILabel!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var pwd: UITextField!
var LoggedInL :Bool?
var mydelegate: WriteValueBackDelegate?
override func viewDidLoad() {
super.viewDidLoad() }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func onSubmit(sender: AnyObject) {
Alamofire.request(.GET, "http://www.jive.com/index.php/capp/user_verification/\(email.text)/\(pwd.text)")
.responseJSON { (_, _, data, _) in
println(data)
let json = JSON(data!)
let name = json["first_name"].stringValue
let status = json["valid_status"].intValue
println(status)
var e = self.email.text
println(e)
self.LoginLabel.text = "Hey \(name)!"
if status == 1{
println("Correect")
self.LoggedInL = true
self.mydelegate?.writeValueBack(true)
}else {
self.LoggedInL = false
println("Error")
}
}
navigationController!.popViewControllerAnimated(true)
}
}
protocol WriteValueBackDelegate {
func writeValueBack(value: Bool)
}
you didn't initialize the delegate, and no need to, delegates are usually for async callbacks. do that instead:
class MainViewController: UIViewController {
static var sharedInstace : MainViewController?;
#IBOutlet weak var LoginButton: UIButton!
var LoggedInL :Bool?
override func viewDidLoad() {
super.viewDidLoad()
MainViewController.sharedInstace = self; //this is better from init function
}
func writeValueBack(value: Bool) {
println("Delegate Method")
if (value == true){
LoginButton.setTitle("My Profile", forState:UIControlState.Normal)
}
}
}
in login view controller
MainViewController.sharedInstance?.writeValueBack(true)
In MainViewControlleryou need a reference of the LoginController instance maybe with an IBOutlet and then set the delegate in viewDidLoad
#IBOutlet weak var loginController : LoginController!
override func viewDidLoad() {
super.viewDidLoad()
loginController.mydelegate = self
}