Swift Adding Image to a Button - image

I want to add an image to a button, and when it is clicked, i want it to change. I'm very new to Swift so I know very little.
I have it like this:
//
// ViewController.swift
// Tip Calculator
//
// Created by ios4 on 10/16/15.
// Copyright (c) 2015 ios4. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var tipAmount: UILabel!
#IBOutlet weak var userBillTextField: UITextField!
#IBOutlet weak var tenOutlet: UIButton!
override func viewDidLoad()
{
tipAmount.text = " "
// var billDouble = (userBillTextField.text as NSString).doubleValue
super.viewDidLoad()
}
#IBAction func calculateButton(sender: UIButton)
{
var billDouble = NSString(string: userBillTextField.text).doubleValue
tipAmount.text = String( stringInterpolationSegment: billDouble * 0.15)
}
#IBAction func tenButton(sender: UIButton)
{
}
and I want the outlet called ten outlet to change to a different image called 10_selected_image from 10_unselected_image.
Any help?
Here are my instructions for this : https://s3.amazonaws.com/mmhighschool/MasterDocs/TipCalculator/TipCalculatorAppDirections.pdf
I'm currently working on stretch 3

You should be able to use set image for control state in your button action
button.setImage(image: UIImage(named: <image name>), forState: UIControlState.Normal)
If you need more info about how to make a "toggle button" this thread has a good answer to that
How to use a UIButton as a toggle switch

For me in Swift 5 is working like:
boton1.setBackgroundImage(UIImage(named: "image Name"), for: UIControl.State.normal)

Related

Go to next screen after save data xcode?

I'm trying to go next screen after the save button is pushed, i tried to write code perform segue and i get buch of errors. Below is my code currently, i didn't finish the save part. I wanted to go back to that later time.
I'm new to coding in xcode, so any advice on where to put this code would be nice.
import UIKit
import CoreData
class SignupVC: UIViewController {
#IBOutlet var txtfirstname: UITextField!
#IBOutlet var txtlastname: UITextField!
#IBOutlet var txtUsername: UITextField!
#IBOutlet var txtPassword: UITextField!
#IBOutlet var txtConfirmpassword: UITextField!
#IBOutlet var txtEmail: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signupTapped(_ sender: Any) {
_ = txtUsername.text;
_ = txtPassword.text;
_ = txtConfirmpassword.text;
_ = txtEmail.text;
//check empty fields
if((txtPassword.text?.isEmpty)! || (txtConfirmpassword.text?.isEmpty)! || (txtEmail.text?.isEmpty)!)
{
//Display alert
displayMyAlertMessage(userMessage: "All fields are required")
return;
}
//check if passwords match
if (txtPassword.text != txtConfirmpassword.text)
{
//Display in alert message
displayMyAlertMessage(userMessage: "Passwords don't match");
return;
}
//store Data
// Display alert message with Confirmation
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
/*
just go into storyboard and hold control key on the button and let it go on the ViewController you want to go to. Then select the kind. For Example "Show"
then it should work. If you have questions ask.

Expression resolves to an unused function

So I have been messing around with saving and calling from NSUserDefaults and I have made progress but I keep on getting this error.
"Expression resolves to an unused function"
The program is supposed to save a string from a textfield so that if you close the program and open it the string will still be their. Unless, you press save again and then the string (Label) will change.
The problem prevents me from running the program so I have not been able to test the new code that I wrote.
Here is the source code feel free to try it. All of this is written in swift.
//
// ViewController.swift
// Help
//
// Created by Lucas on 9/30/15.
// Copyright (c) 2015 Lucas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall()
{
current = Textfield.text!
Label.text = Textfield.text!
Savedlbl.text = Textfield.text!
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
currentDefault.setValue(Saved, forKey: "saved")
currentDefault.synchronize
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The line:
currentDefault.synchronize
should be:
currentDefault.synchronize()

Swift 2.0 animating images

Trying animate series of images in swift 2.0 but following the video tutorials like https://www.youtube.com/watch?v=PSny6un3VUw the method that this guy uses are no longer relevant and swift 2.0 no longer allows arrays to be setup in such means. The basic code this guy used is as follows:
class ViewController: UIViewController: {
#IBOutlet var myImageView: UIImageView
#IBOutlet var animationBtn: UIButton
var imageList = UIImage[]() // no longer valid?
#IBAction func animationBtnClicked(sender: AnyObject) {
startAnimation
}
override func viewDidLoad() {
for i in 1...13
{
let imageName = "\(1)"
imageList += UIImage(named: imageName) //line no longer works
}
}
func startAnimation() -> Void
{
myImageView.animationImages = imageList
myImageView.startAnimation()
}
Anyone know a better way in swift 2.0 to animate images or anyway in general how to do this?
I hope I will help you
#IBOutlet var myImageView: UIImageView!
#IBOutlet var animationBtn: UIButton!
var imageList = [UIImage]()
imageList.append(UIImage(named: imageName))
or
imageList += [UIImage(named: imageName)]

Setting Label text in swift

My first question here. I'm making the jump from Delphi and Pascal to Xcode and Swift and feeling totally overwhelmed by the change.
I'm simply attempting to change the text of a label when a button is clicked. Here is my code from ViewController.swift
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var Label1: NSTextField!
#IBOutlet weak var ChangeText: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ButtonPressed(sender: AnyObject) {
Label1.stringValue = "Hello World"
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
When I run the application as soon as I click the button the application hangs.
I've also tried exchanging stringValue with text but NSTextField does not use this. I can't seem to make the label show up as UITextField.
What am I doing wrong?

Changing image of UIButton via click - XCode 6 Swift

Im simply trying to make it so when I click on a UIButton (for which it currently shows the image of a shell), the image changes into something else (in this case, a coin).
This is what i tried so far and have not had any success. I cant find anything to do this for Swift.Thanks.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lblOutput: UILabel!
#IBOutlet weak var lblWin: UILabel!
#IBOutlet weak var lblLost: UILabel!
#IBOutlet weak var lblWinsAmt: UILabel!
#IBOutlet weak var lblLossesAmt: UILabel!
let coin = UIImage(named: "penny_head") as UIImage;
override func viewDidLoad() {
super.viewDidLoad()
//imgShell1.hidden = true //doesnt work
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnStart(sender: UIButton) {
}
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
The way you're setting up the control is incorrect. Assuming you have a button property named btnShell (and it's the button you want to setup) change your viewDidLoad() method to:
override func viewDidLoad()
{
super.viewDidLoad()
btnShell.setImage(imgShell1, forState:.Normal);
btnShell.setImage(coin, forState:.Highlighted);
}
And then remove the setImage(_:forState:) call from the action method:
#IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
To permanently change the button image on tap, you have to use the .Normal enum case and not .Highlighted for the control state:
sender.setImage(coin,forState: UIControlState.Normal)
Setting the image for the .Highlighted state makes the new image appear only when the button is in that state, i.e. when it is tapped.
If you are looking to change the UIButton's background image permanently you have to use Antonio's method:
sender.setImage(coin,forState: UIControlState.Normal)
This won't change the UIKit's default highlighting when you tap the button. When you don't want the button to be highlighted when you touch it or have different appearances for different states, then you might be better off using an UIImageView.
In viewDidLoad():
imgView?.image = imgOne
imgView?.userInteractionEnabled = true
imgView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "changeImage:"))
The function that changes the image:
func changeImage(recognizer: UITapGestureRecognizer){
self.imgView?.image = imgTwo
}
You can also use isSelected.
button.setImage(image2, for: .normal)
button.setImage(image1, for: .selected)

Resources