Show / Hide Image in Swift - xcode

how to show or hide a image in Swift by taping on a Button?
For example:
i have ImageA and ImageB and one Button which i want to use to move ImageA to ImageB and back to ImageA and so on..
It works perfect to move from ImageA to ImageB, but how can i move back to ImageA?
My code is:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Bild1: UIImageView!
#IBOutlet weak var Bild2: UIImageView!
#IBAction func pressedButton(sender: AnyObject) {
Bild1.hidden = true
Bild2.hidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
Bild1.hidden = false
Bild2.hidden = true
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

override func viewDidLoad()
{
super.viewDidLoad()
Bild1.isHidden = false
Bild2.isHidden = true
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func pressedButton(sender: AnyObject)
{
Bild1.isHidden = !Bild1.isHidden
Bild2.isHidden = !Bild2.isHidden
}

#IBAction func pressedButton(sender: AnyObject) {
Bild1.isHidden = !Bild1.isHidden
Bild2.isHidden = !Bild2.isHidden
}
This will toggle the image property between show and hidden.
Syntax is Swift4 compatible

try replacing with:
#IBAction func pressedButton(sender: AnyObject) {
if Bild1.hidden {
Bild1.hidden = false
Bild2.hidden = true
} else {
Bild1.hidden = true
Bild2.hidden = false
}
}

#IBAction func pressedButton(sender: AnyObject) {
Bild1.hidden = !Bild1.hidden
Bild2.hidden = !Bild2.hidden
}

Related

Use of unresolved identifier 'self'

I am working on a Mac OS X application with Swift.
This is my first time and I thought it would be the same as it is on iOS.
So I got this error (in the title) on this code:
import Cocoa
import AppKit
class LoginViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var passwordTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear() {
}
super.viewDidAppear()
if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && CURRENT_USER!.authData != nil
{
self.logoutButton.hidden = false
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func loginAction(sender: AnyObject)
{
let email = self.emailTextField.text
let password = self.passwordTextField.text
...
}
}
What do I have to write instead of self?
Using self is correct. Try using the property stringValue instead of text.
Here is the code that worked for me:
#IBOutlet weak var emailTextField: NSTextField!
#IBAction func sendTapped(sender: AnyObject) {
let email = self.emailTextField.stringValue
print(email)
}

Why my scrollView is nil?

How can be possible that the scrollview is nil when using the first:#IBAction afegeixGrafic but when using #IBAction func button it isn't'?
I got the class GraficsBalancGlobalViewController which is subclass of the class GraficViewController
class GraficsBalancGlobalViewController: GraficViewController {
#IBAction func afegeixGrafic(sender: NSButton) {
addNewGrafic() // which is set on the GraficViewController
}
}
And when I perform the IBAction afegeixGrafic my program crashes on the line marked below:
class GraficViewController: NSViewController, GraficViewDataSource {
#IBAction func button(sender: NSButton) {
addNewGrafic()
}
func addNewGrafic() {
let frame = NSRect(x: 0, y: 0, width: self.view.bounds.width , height: self.view.bounds.width * 0.25)
let nouGrafic = GraficView(frame: frame)
scrollView.addSubview(nouGrafic) <---- BREAK here!
}
#IBOutlet weak var scrollView: NSView!
//...more code
}
The compiler says that:
fatal error: unexpectedly found nil while unwrapping an Optional value
but the button (IBAction) inside the GraficViewController works well!! So i suppose that the problem is related with the scrollView, but I have no idea of what can be.. It is initialized..
I try this too:
#IBOutlet weak var scrollView: NSView? {
didSet {
guard let sview = scrollView else {
addNewGrafic()
return // because scrollView is nil for some reason, but don't work
}
}
}
Full code:
class GraficsBalancGlobalViewController: GraficViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
#IBAction func afegeixGrafic(sender: NSButton) {
//performSegueWithIdentifier("Nou Grafic", sender: nil)
//let viewController = storyboard!.instantiateControllerWithIdentifier(identifier!) as! GraficsBalancGlobalViewController
addNewGrafic()
}
#IBAction func eliminaGrafic(sender: NSButton) {
}
}
Its nil because of how you instantiated GraficsBalancGlobalViewController. You set it up with a xib or a storyboard however you instantiated it without one.
Do this:
let viewController = storyboard.instantiateControllerWithIdentifier(identifier) as GraficsBalancGlobalViewController
Not This:
let viewController = GraficsBalancGlobalViewController()

swift - adding values between 2 view controllers by prepareforsegue

I have 2 ViewControllers: ViewController1, ViewController2. An "Add" button in ViewController1 will bring up ViewController2. User will then enter in values into ViewController2 which will then be passed back into ViewController1 by prepareforsegue. These values are then append onto the properties of type array in viewcontroller1.
This is being repeated, whereby the user continue pressing the add button to bring up ViewController2 from ViewController1, and then add in new values to be appended onto the properties of array type in ViewController1 via prepareforsegue.
However this is not the case after the first set of values being appended from ViewController2. The second set of values will overwrite the first set of values.
Example.
After the first passed -> force =[1], stiffness[1]
After the second passed -> force=[2], stiffness[2]
I will want this -> force = [1,2], stiffness[1,2]
I want to continue adding until -> force = [1,2,3,4,5], stiffness[1,2,3,4,5]
ViewController1
class ViewController1: UITableViewController, UITableViewDataSource {
var force = [Float]()
var stiffness = [Float] ()
#IBAction func Add(sender: AnyObject) { }
}
ViewController2
class ViewController2: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
#IBAction func submit(sender: AnyObject) {
self.performSegueWithIdentifier("springSubmit", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "springSubmit") {
var svcSubmitVariables = segue.destinationViewController as ViewController1
svcSubmitVariables.force.append(forceVar)
svcSubmitVariables.stiffness.append(stiffVar)
}
The performSegueWithIdentifier method will always initialize new view controller so in your example view controller that showed ViewController2 is different object from object initialized after submitting data and ofc this newly initialized object will have only initialize values. To achieve what you are looking for you will need to declare a function on your ViewController1 that will append data to your arrays, pass that function to ViewController2 and call it on submit method so your view controllers would look similar like these:
ViewController1
class ViewController1: UITableViewController, UITableViewDataSource {
var force = [Float]()
var stiffness = [Float] ()
override func viewWillAppear(animated: Bool) {
//check if values are updated
println(force)
println(stiffness)
}
#IBAction func Add(sender: AnyObject) {
self.performSegueWithIdentifier("viewController2", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if(segue.identifier == "viewController2") {
var addVariables = segue.destinationViewController as ViewController2
addVariables.submitFunc = appendData
}
}
func appendData(newForce:Float,newStiffness:Force){
force.append(newForce)
stiffness.append(newStiffness)
}
}
ViewController2
class ViewController2: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
var submitFunc:((newForce:Float,newStiff:Float)->())!
#IBAction func submit(sender: AnyObject) {
submitFunc(forceVar,stiffVar)
self.dismissViewControllerAnimated(false, completion: nil)
}
}
ViewController
import UIKit
class ViewController: UITableViewController, UITableViewDataSource {
var springNumber:NSInteger = 0
var force = [Float]()
var stiffness = [Float] ()
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return springNumber
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
as UITableViewCell
cell.textLabel!.text = "Spring \(indexPath.row)"
return cell
}
func fwall() -> Float {
for rows in 0..<(springNumber+1) {
force[0] = force[0] + force[rows]
}
force[0] = -(force[0])
return force[0]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = "Springs' Variables"
tableView.registerClass(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
if(springNumber==0) {
force.append(0.0) }
println(force)
println(stiffness)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Adding Values
#IBAction func Add(sender: AnyObject) {
self.performSegueWithIdentifier("addSpring", sender: sender)
}
#IBAction func solve_Pressed(sender: AnyObject) {
self.fwall()
self.performSegueWithIdentifier("Solve", sender: sender)
}
func appendData (newForce: Float, newStiffness:Float, newSpring: NSInteger) {
force.append(newForce)
stiffness.append(newStiffness)
springNumber = newSpring
println(springNumber)
println(force)
println(stiffness)
}
override func prepareForSegue ( segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "addSpring") {
var addVariables = segue.destinationViewController as SpringTableViewControllerInsertVariables
addVariables.submitFunc = appendData
}
if (segue.identifier == "Solve") {
var svcViewController2 = segue.destinationViewController as ViewController2
svcViewController2.forceView2 = self.force
svcViewController2.stiffView2 = self.stiffness
svcViewController2.springNumView2 = self.springNumber
}
if (segue.identifier == "showDetail") {
}
}
}
Code for springTableViewControllerInsertVariables
import UIKit
class SpringTableViewControllerInsertVariables: UIViewController {
var forceVar : Float = 0.0
var stiffVar : Float = 0.0
var springNum : NSInteger = 0
var submitFunc: ((newForce:Float,newStiff:Float,newSpring:NSInteger)->())!
#IBOutlet weak var image: UIImageView!
var imageArray :[UIImage] = [UIImage(named: "springAtWall.jpg")!, UIImage(named:"spring.jpg")!]
override func viewDidLoad() {
if(springNum == 0) {image.image = imageArray[0] }
else {image.image = imageArray[1] }
}
#IBOutlet weak var force: UILabel!
#IBOutlet weak var forceEntered: UITextField!
#IBOutlet weak var stiffness: UILabel!
#IBOutlet weak var stiffnessEntered: UITextField!
#IBAction func checkboxed(sender: AnyObject) {
//when checkedboxed is checked here.
//1)UIImage is changed
//2)calculate2 function is used for calculate1
}
#IBAction func submit(sender: AnyObject) {
//might not work because springNum will be initialise to zero when this viewcontroller starts...
forceVar = (forceEntered.text as NSString).floatValue
stiffVar = (stiffnessEntered.text as NSString).floatValue
springNum = springNum + 1
submitFunc(newForce: forceVar ,newStiff: stiffVar, newSpring: springNum)
self.dismissViewControllerAnimated(false, completion: nil)
}
}

How to use public NSURL Variable

I'm new to Swift and Xcode overall,
I want to create a new public NSURL variable which I want to use later in my code to give it value and use that value later from it. like below :
class AddUrlViewController: NSViewController {
#IBOutlet weak var txtPath: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnFileDialog(sender: NSButton) {
let myFiledialog:NSOpenPanel = NSOpenPanel()
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
var returnCode:NSInteger = myFiledialog.runModal()
if (returnCode == NSOKButton) {
/////////// Use it here
var directoryUrl = myFiledialog.URL?.absoluteURL
}
}
#IBAction func btnStart(sender: NSButton) {
//////////// Use it here
}
}
How should I achieve this the best way ?
Simply define the variable as a property outside of the function scope -
class AddUrlViewController: NSViewController {
#IBOutlet weak var txtPath: NSTextField!
var directoryUrl:NSURL?
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnFileDialog(sender: NSButton) {
let myFiledialog:NSOpenPanel = NSOpenPanel()
myFiledialog.canChooseDirectories = true
myFiledialog.canChooseFiles = false
var returnCode:NSInteger = myFiledialog.runModal()
if (returnCode == NSOKButton) {
/////////// Use it here
self.directoryUrl = myFiledialog.URL?.absoluteURL
}
}
#IBAction func btnStart(sender: NSButton) {
if (self.directoryUrl != nil) {
//////////// Use it here
}
}
}

Programmatically switching views swift

I am trying out apple's new language swift in Xcode 6 beta. I am trying to programmatically switch views when a table view cell is pressed, although all it does is pull up a blank black screen. In my code, I commented out the things that didn't work. They would just make the iOS simulator crash. my code:
// ViewController.swift
// Step-By-Step Tip Calculator
// Created by Dani Smith on 6/17/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
import UIKit
var billTotalPostTax = 0
class BillInfoViewController: UIViewController {
//outlets
#IBOutlet var totalTextField: UITextField
#IBOutlet var taxPctLabel: UILabel
#IBOutlet var resultsTextView: UITextView
#IBOutlet var taxPctTextField : UITextField
//variables
var billTotalVar = ""
var taxPctVar = ""
//actions
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func stepOneNextPressed(sender : AnyObject)
{
billTotalVar = totalTextField.text
taxPctVar = taxPctTextField.text
}
#IBAction func calculateTipped(sender : AnyObject)
{
tipCalc.total = Double(totalTextField.text.bridgeToObjectiveC().doubleValue)
let possibleTips = tipCalc.returnPossibleTips()
var results = ""
for (tipPct, tipValue) in possibleTips
{
results += "\(tipPct)%: \(tipValue)\n"
}
resultsTextView.text = results
}
/*
#IBAction func taxPercentageChanged(sender : AnyObject)
{
tipCalc.taxPct = String(taxPctTextField.text) / 100
refreshUI()
}*/
#IBAction func viewTapped(sender : AnyObject)
{
totalTextField.resignFirstResponder()
}
let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06)
func refreshUI()
{
//totalTextField.text = String(tipCalc.total)
}
}
class RestaurantTableViewController: UITableViewController
{
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
let row = indexPath?.row
println(row)
//let vc:BillInfoViewController = BillInfoViewController()
//let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo") as UINavigationController
//self.presentViewController(vc, animated: true, completion: nil)
}
}
Thank you so much for all of your help.
I just figured it out. I had to make
let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")`
to be
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")
to silence a warning. I then changed presentViewController to showViewController, and it worked. Here is my completed class:
class RestaurantTableViewController: UITableViewController
{
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
let row = indexPath?.row
println(row)
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("billInfo")
self.showViewController(vc as UIViewController, sender: vc)
}
}
let vc = self.storyboard.instantiateViewControllerWithIdentifier("billInfo") as! BillInfoViewController
self.presentViewController(vc, animated: true, completion: nil)
LE: downcast added

Resources