Changing image of UIButton via click - XCode 6 Swift - xcode

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)

Related

How to change button image in swift?

I am working on an app which has a button. The button has no text, image or background.
So what I want to do is to give it an image in the viewDidLoad function.
This is what I have:
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage("redTap.png", forState: UIControlState.Normal)
}
But I have an error that says I can not convert string to UIIMage.
How do I get it to work?
I have tried:
let image = UIImage(named: "redTap.png")
tapButton.setImage(image, forState: UIControlState.Normal)
I have gotten it to work but now I have a problem.
The image is suppose to be a red text but it shows up blue.
I was able to get the image to show correctly by using:
let image = UIImage(named: imageColor[randNum])?.imageWithRenderingMode(.AlwaysOriginal)
tapButton.setImage(image, forState: UIControlState.Normal)
What I want now is to not have the button be highlighted when the button is pressed. I have a few other buttons that have images assigned to them in xcode and not through code. They don't highlight when pressed.
So how can I get rid of highlighting when the button is pressed?
You don't need ".png".
If ".imageWithRenderingMode(.AlwaysOriginal)" is working for you: To keep the same image in different states, you have to set the same image/properties for the different states.
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
tapButton.setImage(UIImage(named: "redTap")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Highlighted)
}
Swift 3
yourBtn.setImage( UIImage.init(named: "imagename"), for: .normal)
now (swift 3 edition):
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
tapButton.setImage(UIImage(named: "redTap")?.withRenderingMode(.alwaysOriginal), for: .normal)
}
First I would put the image you wanted inside the Assets.xcassets folder. Just drag it in. Then you can call it whatever you want by double-clicking on it. Lets say that it is called "redTap".
For code you would put:
#IBOutlet var tapButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let redTapImage = UIImage(named: "redTap")
tapButton.setImage(redTapImage, forState: UIControlState.Normal)
}
There's one simple solution:
#IBOutlet var tapButton: UIButton!{
didSet{
let image = UIImage(named: imageColor[randNum])
tapButton.setImage(image, forState: UIControlState.Normal)
}
Besides that, in the Attribute Inspector, Set Button type to 'Custom'
First set your button type as Custom in interface builder and set the image for normal state for your button.
Connect IBOutlet for button in class file as
#IBOutlet weak var btnCheckbox: UIButton!
in your class file in viewDidLoad set image for selected state as
btnCheckbox.setImage(UIImage.init(named: "name_of_image"), for: .selected)
Create #IBAction for in class file as
#IBAction func onTapCheckBox(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
}
Then connect #IBAction to your button's Touch up Inside event from interface builder
Let image = UIImage(named : "redTap.png")
tapButton.setImage(image, .Normal)
let button = UIButton(type: .Custom)
let image = UIImage(named:"redTap")?.imageWithRenderingMode(.AlwaysTemplate)
button.setImage(image, forState: .Normal)
button.tintColor = UIColor.redColor()
Update For latest swift versions,
It works this way
button.setImage(UIImage(named: "propopup")?.withRenderingMode(.alwaysOriginal), for: [])

Swift Adding Image to a Button

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)

Trigger Segue Artificially

I am trying to pass data between two viewContollers in an OS X storyboard application using Swift. When I press a button on VC1, it opens VC2, and prepareForSegue is run. However, I can't pass data back to VC1 because a. prepareForSegue isn't being run (because a window isn't being opened) and b. because even if it were, VC1 doesn't know data is being sent and I can't figure out a function (something like viewDidBecomeFocus, if such a function existed) to let it know to look. I feel like there must be a way to do this.
If you know of a way to do this in IOS but not OSX, it could still be useful.
Thanks!
Let assume that in your first ViewController you have one label and one button. When pressed, that button open popover (SecondViewController) with one textfield (and one button what says ready or close etc.), where you want take its value and assign it to your label. That is where delegates and protocols come handy.
SecondViewController:
#objc protocol TextDelegate {
func passedString(textValue: String)
}
class SecondViewController: NSViewController {
#IBOutlet weak var textField: NSTextField!
weak var delegate: TextDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
#IBAction func closePopOver(sender: AnyObject) {
if delegate != nil {
delegate!.passedString(textField.stringValue)
}
self.dismissViewController(self)
}
}
This is ViewController:
#IBOutlet weak var myLabel: NSTextField!
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "mySegue" {
let vc = segue.destinationController as! SecondViewController
vc.delegate = self
}
}
func passedString(textValue: String) {
myLabel.stringValue = textValue
}

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?

How to use gesture to move large image in a view using swift

I can able to do pinch zoom using pinch gesture using swift. But after image enlarges, i can't able view the which is out of view. (i.e)can't able to move image around the screen. Can any one help me?
My code:
#IBAction func scaleImage(sender: UIPinchGestureRecognizer) {
sender.view!.transform = CGAffineTransformScale(sender.view!.transform, sender.scale, sender.scale)
sender.scale = 1
}
I need to view full image after zooming it.
Add ScrollView and add image on scrollView
class ViewController:UIScrollViewDelegate{
#IBOutlet var imageView: UIImageView!
#IBOutlet var scroll: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scroll.maximumZoomScale=4;
scroll.minimumZoomScale=1.0;
scroll.bounces=true;
scroll.bouncesZoom=true;
scroll.contentSize=CGSizeMake(imageView.frame.size.width, imageView.frame.size.height);
scroll.showsHorizontalScrollIndicator=true;
scroll.showsVerticalScrollIndicator=true;
scroll.delegate=self;//assigning delegate
self.scroll.addSubview(imageView);
self.view.addSubview(scroll);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewForZoomingInScrollView(_ scrollView: UIScrollView) -> UIView?
{
return self.imageView
}
}

Resources